简体   繁体   English

不使用python中的sum函数对2D列表的行求和

[英]Summing rows of a 2D list without using sum function in python

I have a listed called numbers and I am writing code to sum the rows then sum the result of those sums (ie sum the column). 我有一个列出的被称为数字,我正在编写代码以对行求和,然后对这些求和的结果求和(即对列求和)。 I am supposed to write the code without the sum function. 我应该写没有sum函数的代码。 What I have so far is pasted below. 到目前为止,我粘贴的内容如下。 It gives me close to the right output but is just slightly off and I don't know what the deal is. 它使我接近正确的输出,但略有偏离,我不知道这笔交易是什么。

total=0

for row in numbers:
  for i in row:
      total+=int(i)
  print(total)

grandtotal=0
for cols in row:
  grandtotal+=total
print(grandtotal)

You need to reset total back to zero for each row. 您需要将每一行的total重置为零。 And since you aren't saving the row totals anywhere you need to accumulate the grandtotal at the end of each row loop, not in a separate loop 而且,由于你没有保存该行总计任何地方,你需要积累的grandtotal在每行循环的结束,而不是在一个单独的环

numbers = [
    [1, 1, -2],
    [-1, -2, -3],
    [1, 1, 1],
]

grandtotal = 0
for row in numbers:
    total = 0
    for i in row:
        total += i
    print(total)
    grandtotal += total
print(grandtotal)

output 产量

0
-6
3
-3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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