'How to find sum of a certain element in 2d
recLst=[["10:20","DDSFE","Dyson Digital Slim Fluffy Extra",2599.0,"Iron"],["10:25","DV8SF","Dyson V8 Slim Fluffy Plus",1799.0,"Standard"],["13:30","DDSFE","Dyson Digital Slim Fluffy Extra",2599.0,"Purple"],["13:30","DDSFE","Dyson Digital Slim Fluffy Extra",2599.0,"Iron"],["16:15","DV11F","Dyson V11 Fluffy",2899.0,"Red"],["17:25","DV8SF","Dyson V8 Slim Fluffy Plus",1799.0,"Standard"]]
for e in recLst:
if e[1]=='DDSFF':
print(e)
#This will be the layout
['10:20', 'DDSFE', 'Dyson Digital Slim Fluffy Extra', 2599.0, 'Iron']
['13:30', 'DDSFE', 'Dyson Digital Slim Fluffy Extra', 2599.0, 'Purple']
['13:30', 'DDSFE', 'Dyson Digital Slim Fluffy Extra', 2599.0, 'Iron']
hi, I wanna ask how do I find for the sum of the float for three of the list, the thing is that I print the three list above by using a for loop but I don't have any idea on sum three of the element up, I try using a list and append all the data that I need into it, but the list will only have item inside
I want to find the sum for the 4th element in my list, but I have no idea how since I'm using a for loop (by the way I am a new learner so pls don't scold me if I act stupid or don't understand the explanation)
Solution 1:[1]
If you're trying to sum the 4th element of the list, you could use the following:
list_sum = 0
for e in recLst:
if e[1] == "DDSFE":
list_sum += e[4]
print(list_sum)
This is assuming of course, each e in recLst is a list with
5 elements.
To be safe:
list_sum = 0
for e in recLst:
if len(e) == 5 and e[1] == "DDSFE" and isinstance(e[4], float):
list_sum += e[4]
print(list_sum)
Not sure if you need it to be this involved.
Or you could do the following:
list_sum = sum([e[3] for e in recList if len(e) == 5 and e[1] == "DDSFE" and isinstance(e[3], float)])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ewong |
