首页 > 解决方案 > 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.

标签: pythonarrayslist

解决方案


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)

推荐阅读