TypeError:列表索引必须是整数,而不是list.怎么修? [英] TypeError: list indices must be integers, not list. How to fix?
问题描述
其中包含带有TypeError的代码. 列表索引必须是整数,而不是列表",尽管它们是整数.非常感谢您帮助我找出问题所在.我需要从源7x5选项卡中获得具有不同值的矩阵7x5.错误发生在最后一行.
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-1
和其他内容)中的IndexError
(列表超出范围).虽然,我不认为这确实是python-way.我也非常感谢您对此事的帮助.
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])
这是发生错误的地方.如果i
,j
已经是int
,我不知道该如何解决.
This is where error occurs. I don't get what should I fix if i
, j
are already int
.
推荐答案
i
和j
不是索引;它们是lines
列表中的值. Python for
循环是 for-each构造.
i
and j
are not indices; they are values from the lines
list. Python for
loops are for-each constructs.
使用:
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])
其中,当i
和/或j
为0
时,% len()
计算将回绕"到T
或T[i]
中的最后一个条目. enumerate()
函数将索引添加到循环中.
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.
这确实假定您已经在T
中预构建了列表结构的嵌套列表.
This does assume you already pre-built a nested list of lists structure in T
.
这篇关于TypeError:列表索引必须是整数,而不是list.怎么修?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!