问题
New in Python, help. Why i get this error: "TypeError: list indices must be integers, not tuple,"
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
回答1:
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 = [[0] * len(tables) for _ in range(len(tables))]
回答2:
A dictionary will get you the assignment behavior you desire:
imheight = {}
But if 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.
回答3:
Not
imheight[i,j] = hij
It should be written like this:
imheight[i:j] = hij
It means the index from i to j.
来源:https://stackoverflow.com/questions/19780320/typeerror-list-indices-must-be-integers-not-tuple-whats-wrong