简体   繁体   中英

How to calculate the total of each list, in a list of lists Python

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.

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)

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

只需使用总和即可。

[sum(x) for x in ll]

You can use sum in a for loop:

total = []   
for i in list_of_lists:
    total.append(sum(i))

print(total)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM