[英]How to add the values of a nested list without using sum built in function and using a nested loop
I have the following line of code我有以下代码行
grades=[[54,67,18,19],[89,98,99,98],[26,16,13]]
How can I add the values of each nested list without using the sum built in method and using a nested for loop?如何在不使用 sum 内置方法和使用嵌套 for 循环的情况下添加每个嵌套列表的值?
grades=[[54,67,18,19],[89,98,99,98],[26,16,13]]
sum = 0 # Acumulator
for l in grades: # For each list in grades
for g in l: # For each grade in current list
sum += g # Sum current grade into the acumulator
print(sum) # Return 597
How can I add the values of each nested list
如何添加每个嵌套列表的值
see below (assuming you want to sum each nested list)见下文(假设你想总结每个嵌套列表)
totals = []
avg = []
grades=[[54,67,18,19],[89,98,99,98],[26,16,13]]
for g in grades:
totals.append(0)
for x in g:
totals[-1] += x
avg.append(totals[-1]/len(g))
print(totals)
output output
[158, 384, 55]
You can make use of reduce to find the sum of elements in the list as below:您可以使用 reduce 来查找列表中元素的总和,如下所示:
import functools
grades=[[54,67,18,19],[89,98,99,98],[26,16,13]]
total = 0
res = []
for grade in grades:
res.append(functools.reduce(lambda x, y: x+y, grade))
print(res) #[158, 384, 55]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.