【问题标题】:What am I missing because I keep getting a, "TypeError: list indices must be integers or slices, not list"我错过了什么,因为我不断收到“TypeError:列表索引必须是整数或切片,而不是列表”
【发布时间】:2020-10-30 11:24:52
【问题描述】:

我目前正在尝试在 python3 中逐项执行 for 循环。我可能会错过什么?

def add_rows(sq_list):
    rowNum = [[0, 0, 0],
              [0, 0, 0],
              [0, 0, 0]]
    
    for row in rowNum:
        total = 0
        for column in sq_list[row]:
            total += column
            
        print("Row total is:", total)
    
add_rows([[1, 3, 8],
          [2, 4, 6],
          [7, 9, 0]])

【问题讨论】:

  • 首先你应该在这里输入你的代码,而不是图像。
  • 您的预期输出是什么?有什么错误?你为什么用图片而不是在这里输入?

标签: python python-3.x


【解决方案1】:

当您遍历行时,行是整个列表。所以你的第二次迭代应该超过单个元素。所以它应该看起来像这样(例如):

for row in rowNum:
    total = 0
    for element in row:
        total += element
    
    print(...)

【讨论】:

  • 请不要回答诸如此类的问题。
  • 是的,我想这就是我被否决的原因;'(但我试图纠正他的问题,因为他是新人。
猜你喜欢
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 2019-07-04
  • 2015-12-09
  • 2021-11-28
相关资源
最近更新 更多