【问题标题】:The sum of a 2D arrays' specific rows - Python二维数组特定行的总和 - Python
【发布时间】:2017-03-16 22:51:42
【问题描述】:

试图让这个程序打印每一行的总和,然后是所有元素的总和,总和没问题,但我不明白为什么行的各个总和输出不正确

rows = len(numbers)
cols = len(numbers[0])
total=0

变量设置如上(每列长度相同,数组全为整数)

我希望它遍历每一行,在该行中添加每一列并打印它,然后打印整个数组的总数。

for x in range(0, rows):
  rowtotal=0
  for y in range(0, cols):
    rowtotal=rowtotal+int(numbers[x-1][y-1])
  print(rowtotal)
  total=total+rowtotal
print(total)

数组是通过导入的 import sys numbers= sys.argv[1:] for i in range(0,len(numbers)): numbers[i]= numbers[i].split(',')

我正在通过在线软件进行编码,这可能是问题所在。目前它返回

程序输入失败:1,1,-2 -1,-2,-3 1,1,1 预期输出: 0 -6 3 -3 您的程序输出: 3 0 -6 -3

任何其他代码,包括numbers[x][y] 似乎总是返回错误

【问题讨论】:

  • 你能打印数组编号吗?

标签: python arrays 2d file-handling


【解决方案1】:

您应该使用numbers[x][y] 而不是numbers[x-1][y-1]

如果你这样做:

numbers=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
rows = len(numbers)
cols = len(numbers[0])
total=0
for x in range(0, rows):
    rowtotal=0
    for y in range(0, cols):
        rowtotal=rowtotal+int(numbers[x][y])
    print(rowtotal)
    total=total+rowtotal
print(total)

输出是

6
15
24
33
78

此外,如果数组numbers 仅包含整数,您可以从int(numbers[x][y]) 中删除int

【讨论】:

  • 谢谢,但返回错误 IndexError: list index out of range
  • 您是否正确定义了二维数组编号?我在答案中添加了一个运行示例。我运行它,它对我有用。
  • 数组已导入(这是正确的术语吗?)我已经编辑了问题
  • 你能在问题中添加一个数组的例子吗?听起来数组的格式可能会导致问题。即打印数组编号。
  • 没有要打印的数字?另外,如果我删除了 int(),则会出现 TypeError: unsupported operand type(s) for +: 'int' and 'str' 我通过在线软件进行编码,所以这可能是问题所在?我真的很困惑....
猜你喜欢
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 2021-02-23
相关资源
最近更新 更多