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
错误是由于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]]