【问题标题】:Reason for IndexError occurrence [duplicate]发生 IndexError 的原因 [重复]
【发布时间】:2021-10-15 12:48:22
【问题描述】:
list1 = [[1,2],[3,4]]
list2 = [[2,3],[4,5]]

def function(a,b):
    answer =[]
    for i in range(len(a)):
        for j in range(len(a[0])):
            answer[i][j] = a[i][j] + b[i][j]
    return answer

print(function(list1,list2))

我是 python 新手。我不知道为什么会出现这个错误。

IndexError: list index out of range

【问题讨论】:

  • for j in range(len(a[0])) 的长度为a[0] 或嵌套列表

标签: python list indexoutofrangeexception outofrangeexception


【解决方案1】:

错误是因为answer[i][j] = a[i][j] + b[i][j],因为answer =[]

您试图通过索引将值分配给一个空列表,因此它会抛出 IndexError

您需要创建具有所需大小的虚拟值的列表

list1 = [[1,2],[3,4]]
list2 = [[2,3],[4,5]]
def function(a,b):
    answer = [[0 for _ in _] for _ in a] #<---- zero values [[0, 0], [0, 0]]
    for i in range(len(a)):
        for j in range(len(a[0])):
            answer[i][j] = a[i][j] + b[i][j]
    return answer
print(function(list1,list2))

#output: [[3, 5], [7, 9]]

,或者需要使用append/extend可变操作:

def function(a,b):
    answer = []
    for i in range(len(a)):
        row = []   #<---- create an empty list for inner list
        for j in range(len(a[0])):
            #answer[i][j] = a[i][j] + b[i][j]
            row.append(a[i][j] + b[i][j])   #<---Append each values to row
        answer.append(row)    #<--- Append row to answer list
    return answer
print(function(list1,list2))
#output: [[3, 5], [7, 9]]

【讨论】:

  • 谢谢,我现在明白了。如果列表为空,我无法通过索引为列表分配值!非常感谢
  • 不仅是空的,如果索引不存在的话。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 2011-06-19
  • 2020-10-18
  • 1970-01-01
  • 2010-10-15
  • 1970-01-01
相关资源
最近更新 更多