Python 3.x Python-负数不相加,正数相加

Python 3.x Python-负数不相加,正数相加,python-3.x,Python 3.x,我应该把这些行和所有数字的总和加起来。我可以把总数加起来,但是我不能把只有负数的行加起来。以下代码将正数相加,但负数相加不正确 grandTotal = 0 sumRow = 0 for x in range(len(numbers)): sumRow = (sumRow + x) print(sumRow) for x in range(len(numbers)): for y in range(len(numbers[x])): grandTotal = grand

我应该把这些行和所有数字的总和加起来。我可以把总数加起来,但是我不能把只有负数的行加起来。以下代码将正数相加,但负数相加不正确

grandTotal = 0
sumRow = 0

for x in range(len(numbers)): 
  sumRow = (sumRow + x)
  print(sumRow)

for x in range(len(numbers)):
  for y in range(len(numbers[x])):
    grandTotal = grandTotal + int(numbers[x][y])

print(grandTotal)
当用户输入为:

1,1,-2 -1,-2,-3 1,1,1
我的输出是:0 1. 3. -三,

而不是:0 -6 3. -三,

我知道这和第一个for循环有关,但我想不出来。当我尝试这个:

grandTotal = 0
sumRow = 0

for x in range(len(numbers)): 
  sumRow = (sumRow + (numbers[x]))
  print(sumRow)

for x in range(len(numbers)):
  for y in range(len(numbers[x])):
    grandTotal = grandTotal + int(numbers[x][y])

print(grandTotal) 
我收到错误消息:

File "list.py", line 14, in 
sumRow = (sumRow + (numbers[x]))
TypeError: unsupported operand type(s) for +: 'int' and 'list'
为什么我的代码不加负数?非常感谢您的帮助

你说什么

sumRow = (sumRow + (numbers[x]))
要添加整数,您可以说是1+1,而不是(1+(1)),这将添加到列表中,以便您可以更改它。 根据我的理解,数字也是一个数组

numbers[x]
会给你很多数字。您需要的是每行的总数,以及所有行的总数。这里有一个程序可以做到这一点。我假设您的程序自动从用户输入中获取数字

grandTotal = 0
for row in numbers:
    #for each row we find total amount
    rowTotl = 0
    for value in row:
        #for each column/ value we add tot the row total
        rowTotl += value
    print(rowTotl)
    #add this row's value to the grandTotal before we move on
    grandTotal += rowTotl
#After all adding we print grand total
print(grandTotal)
程序不添加负数的原因实际上是因为行总数根本不添加数字。它们只是添加索引,而不是值,因此它们也不适用于正数。总计之所以有效,是因为您正确地添加了所有值,而不是添加了索引。仅供参考

for index in range(len(numbers)) :
不提供值,而是:0,1,2,3,4,5,6…(索引)直到范围结束,以获取您要执行的值编号

for value in numbers:

什么是数字?非常感谢您的解释。这是非常有用的。