获取类型错误:列表索引必须是整数,而不是元组
问题描述:
我想实现的算法,但要得到一个错误,我不知道是什么原因:获取类型错误:列表索引必须是整数,而不是元组
size = len(data)
total = sum(data)
barray = [[False for x in range(int(size+1))] for x in range(int((total/2)+1))]
for x in range(0,size):
barray[0][x] = True
for x in range(1,int(total/2)):
barray[x][0] = True
for i in range(1,int(total/2)):
for j in range(1,size):
barray[i,j] = (barray[i, j - 1] or barray[i - data[j - 1], j - 1]) if data[j-1] <= i else barray[i, j - 1]
return barray[int(total/2),size]
错误:
Traceback (most recent call last):
File "C:/Users/tuf21741/PycharmProjects/PyBackup/test.py", line 25, in <module>
assert checkio([10, 10]) == 0, "1st example"
File "C:/Users/tuf21741/PycharmProjects/PyBackup/test.py", line 17, in checkio
barray[i,j] = (barray[i, j - 1] or barray[i - data[j - 1], j - 1]) if data[j-1] <= i else barray[i, j - 1]
TypeError: list indices must be integers, not tuple
答
barray[i,j] = (barray[i, j - 1] or barray[i - data[j - 1], j - 1]) if data[j-1] <= i else barray[i, j - 1]
看起来你应该在这里为你的索引使用单独的方括号。
barray[i][j] = (barray[i][j - 1] or barray[i - data[j - 1]][j - 1]) if data[j-1] <= i else barray[i][j - 1]
并且对于return语句也是如此。
return barray[int(total/2)][size]
' 'B [I,J]'!= 'B [i] [j]''使用时numpy的(或类似的)阵列 – jonrsharpe
这(在OPS)语法是唯一正确的。 –
[Python的列表索引必须是整数,而不是元组的“可能的重复”(http://stackoverflow.com/questions/9367813/python-list-indices-must-be-integers-not-tuple-error) –