Reputation: 223
I have collected a list of lists, each list representing data from a single day. I need to find the SUM of these to calculate the total volume each day. I can only seem to add together each list, not an individual lists data.
Provides the total of all the lists, not each individual lists total.
for ele in range(0, len(y_pred)):
total = total + y_pred[ele]
print (total)
Expected 18 outputs, each lists sum, not one output with a sum of everything.
Upvotes: 0
Views: 2282
Reputation: 67
You can use sum
in a for
loop:
total = []
for i in list_of_lists:
total.append(sum(i))
print(total)
Upvotes: 1
Reputation: 727
First of all, you don't need to use this pattern in Python:
for ele in range(0, len(y_pred)): # let's not use "ele" as a var name, btw. confusing
total = total + y_pred[ele]
because you can just write:
for element in y_pred:
total = total + element
Anyway, you could use map
as another poster suggested, but the simplest way is to just extend your existing pattern. Since you have a list within a list, you have two lists to iterate through:
for sub_list in mega_list:
for element in sub_list:
total += element
Upvotes: 2
Reputation: 22776
Use map
and sum
:
sums = list(map(sum, list_of_lists))
where list_of_lists
is the list that contains other lists. Now, sums
is a list containing the sum of each sub-list. To get the entire sum, use sum
again with the new sums
list:
sum(sums)
Upvotes: 2