【问题标题】:Sum columns in 2-D array. TypeError: list indices must be integers or slices, not tuple对二维数组中的列求和。 TypeError:列表索引必须是整数或切片,而不是元组
【发布时间】:2016-12-14 22:18:50
【问题描述】:

尝试对每一列中的所有整数求和,存储每个总和 在一个列表中。当我运行代码时,它会产生一个类型错误 = 列表索引必须是整数或切片,而不是元组。

array = [[3, 5, 7, 9]
        [2, 7, 3, 5],
        [1, 2, 6, 3],
        [6, 9, 5, 3]]

column_sum = []
total = 0
i = 0
for row in aList:
    total = total + row[i]
    column_sum.append(total)
    total = 0
    i = i + 1
print(column_sum)

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您的错误是array 第一行后缺少逗号。此外,您在 for 循环中通过 aList 引用 array

    通过这些更改,您的代码将运行,但我认为它不会为您提供您想要获得的结果。我想这就是你想要的:

    array = [[3, 5, 7, 9],
            [2, 7, 3, 5],
            [1, 2, 6, 3],
            [6, 9, 5, 3]]
    
    column_sum = [0, 0, 0, 0]
    for row in array:
        for i, element in enumerate(row):
           column_sum[i] += element
    print(column_sum)
    

    请注意,这种编写方式非常低级且非 Pythonic。你应该考虑使用 NumPy 来做这些事情。

    【讨论】:

      猜你喜欢
      • 2017-10-02
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多