简体   繁体   English

二维列表汇总

[英]Summation of a 2d list

I am having trouble adding up each row in a 2d list. 我在将二维列表中的每一行加起来时遇到麻烦。

Here is the problem:We will pass in a 2 dimensional list of numbers. 问题出在这里:我们将传入二维数字列表。 You should: 1 . 您应该:1。 add up all the numbers in each row and output that number and 2. output the grand total of all rows. 将每一行中的所有数字相加并输出该数字,然后输出2.所有行的总计。

Below is my code so far: 下面是我到目前为止的代码:

    import sys
    numbers= sys.argv[1:]


    for i in range(0,len(numbers)): 
      numbers[i]= numbers[i].split(',')
    total = 0
    sum = 0
    for row in range(len(numbers)):
      sum += (row)
      total += (sum)
      print(sum)
    print(total)

Here is what my output and the expected output is: 这是我的输出和预期的输出是:

Program Output 节目输出

Program Failed for Input: 1,1,-2 -1,-2,-3 1,1,1
Expected Output: 0
-6
3
-3

Your Program Output: 0
1
3
4

Your output was incorrect. 您的输出不正确。 Try again. 再试一次。

As you can see, I have everything correct except for the 2nd row which is adding all negative numbers which is then affecting the grand total at the end. 如您所见,除了第二行添加了所有负数之后,我一切都正确,这将影响最后的总计。 Do I need add negative numbers differently? 我需要以不同的方式加上负数吗?

Thanks for you input! 感谢您的输入!

You first need to (after splitting your input by ',') change splitted values from strings to integers and then you could use python builtin function sum to add them all up. 首先,您需要(将输入除以','之后)将拆分后的值从字符串更改为整数,然后可以使用python内置函数sum将它们加起来。

import sys

numbers= sys.argv[1:]

total = 0
for i in numbers:
    row_sum = sum([int(i) for i in i.split(',')])
    total += row_sum
    print(row_sum)
print(total)

Output: 输出:

0
-6
3
-3

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

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