TypeError: list indices must be integers, not list. How to fix?

五迷三道 提交于 2019-11-28 07:44:13

问题


There's the code with the TypeError in it. "list indices must be integers, not list", though they are integers. I'd appreciate you helping me figure out what's wrong. What I need is to get matrix 7x5 from source 7x5 tab with different values. The error occurs on the last line.

lines = []

with open("text.txt") as f:
    for line in f:
        line = [int(x) for x in line if (x != ' ') and (x != '\n')]
        lines.append(line)
    f.close()

What I have after reading file is list of lists with numbers called "lines". It's integers. Not strings. Like:

>> [[1, 2, 3...], [4, 5, 6...], [7, 8, 9...],[...]]


i = 1
j = 1
T = []
T.append(lines[0][0]) 

I made this for avoiding IndexError (list out of range) on last line (i-1 and stuff). Though, I don't think it's python-way really. I'd appreciate help with this thing too.

for i in lines:
    for j in lines:
        T[i][j] = lines[i][j] + max(T[i][j-1], T[i-1][j])

This is where error occurs. I don't get what should I fix if i, j are already int.


回答1:


i and j are not indices; they are values from the lines list. Python for loops are for-each constructs.

Use:

for i, line in enumerate(lines):
    for j, value in enumerate(line):
        T[i][j] = value + max(T[i][j - 1 % len(T[i])] + T[i - 1 % len(T)][j])

where the % len() calculations 'wrap around' to the last entry in T or T[i] when i and / or j are 0. The enumerate() function adds indices to the loop.

This does assume you already pre-built a nested list of lists structure in T.




回答2:


for i in lines:
    for j in lines:

i and j iterate over the elements of lines, not the indices. That means i and j are always lists, entire lines of numbers.

If you want to go over the indices (usually you don't, but it may be the best option here), you want

for i in range(len(lines)):
    for j in range(len(lines[i])):

This is awkward by design, as the Python designers want people to default to iterating over the elements of a sequence.

Also, note that your loop tries to access elements of lines before the first row and before the first column. Perhaps you want to start your loops on the second row and column.



来源:https://stackoverflow.com/questions/22431647/typeerror-list-indices-must-be-integers-not-list-how-to-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!