Python 类型错误:列表索引必须是整数,而不是元组,出了什么问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19780320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: list indices must be integers, not tuple, whats wrong
提问by John Wrt
New in Python, help. Why i get this error: "TypeError: list indices must be integers, not tuple,"
Python 中的新手,帮助。为什么我收到此错误:“类型错误:列表索引必须是整数,而不是元组”
imheight = []
for i in range(0,len(tables)):
for j in range(0,len(tables)):
hij = computeHeight(imp[i],imp[j],'Meter')
imheight[i,j] = hij
imheight[j,i] = hij
回答by óscar López
This syntax is wrong:
这个语法是错误的:
imheight[i,j] = hij
imheight[j,i] = hij
Perhaps you meant this?
也许你是这个意思?
imheight[i][j] = hij
imheight[j][i] = hij
But then again, imheight
is a one-dimensional list, but you're assuming that it's a two-dimensional matrix. It will only work if you first initialize imheight
correctly:
但话又说回来,它imheight
是一个一维列表,但您假设它是一个二维矩阵。它只有在您首先imheight
正确初始化时才有效:
imheight = [[0] * len(tables) for _ in range(len(tables))]
回答by kindall
A dictionary will get you the assignment behavior you desire:
字典将为您提供您想要的分配行为:
imheight = {}
Butif you later need to iterate over it in some order, this won't be as easy as if you'd done it as a proper list of lists, since dictionaries don't maintain order. However, this may work well enough.
但是,如果您以后需要以某种顺序对其进行迭代,这将不像您将它作为一个适当的列表列表那样容易,因为字典不维护顺序。但是,这可能工作得很好。
回答by Belter
Not
不是
imheight[i,j] = hij
It should be written like this:
应该这样写:
imheight[i:j] = hij
It means the index from i to j.
它表示从 i 到 j 的索引。