【问题标题】:Getting TypeError: list indices must be integers, not tuple获取 TypeError:列表索引必须是整数,而不是元组
【发布时间】:2014-07-13 01:16:42
【问题描述】:

我正在尝试实现该算法,但一直出错,我不确定为什么:

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

【问题讨论】:

标签: python algorithm


【解决方案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]

看起来您应该在此处为索引使用单独的方括号。

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]

【讨论】:

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