python - 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)
推荐阅读
- python - Python 评论:为什么代码 1 产生的结果与代码 2 不同?
- azure-devops - Azure Pipeline - 为什么需要参数值
- datetime - 可以在没有日期信息的情况下解析时间字符串吗?
- spring - spring boot 2.1.3 以后抛出循环引用
- flutter - 我有一个关于在 initstate 中使用异步函数的问题
- redis - 如何将 aof 文件重新加载到 Redis
- javascript - 如何将径向 CanvasGradients 与 Chart.js 的圆环图一起使用?
- angular - Storybook:在组件级别注入一个模拟的提供者/服务
- coq - `match goal` 不匹配 let 解构表达式
- ios - SwiftUI String 符合 Identifiable 似乎不正确