简体   繁体   English

如何在不使用 function 中内置的求和和使用嵌套循环的情况下添加嵌套列表的值

[英]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.

相关问题 如何在不使用任何导入或总和 function 的情况下对嵌套列表中的列值求和? - How do I sum the column values in a nested list without using any imports or the sum function? 使用“ for循环”求和嵌套列表值并返回(总和) - Using 'for loop' to sum nested list values and return (total of sum) 不使用SUM函数的嵌套列表的总和(练习) - Sum of nested list without using SUM function (exercise) 嵌套列表:如何使用 for 循环对这些列表中索引 1 和 2 中的所有元素求和? - Nested list: How to sum all of the element in index 1 & 2 in these list by using for loop? 使用 for 循环的嵌套列表中元素的总和 - Sum of elements in nested list using for loop 不使用itertools查找嵌套列表的总和 - Finding the sum of a nested list without using itertools 递归 function 在嵌套列表中找到最小值,而不使用 for 循环 - Recursive function to find the minimum value in a nested list, without using a for loop 如何使用嵌套 for 循环创建嵌套列表? - How to Create a nested list using nested for loop? 使用 lambda 函数在嵌套列表中查找总和 - Finding a sum in nested list using a lambda function 如何使用嵌套 for 循环将值添加到 Pandas Dataframe? - How to add values to a Pandas Dataframe using a nested for loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM