TypeError: list indices must be integers, not tuple, whats wrong [duplicate]

北慕城南 提交于 2019-12-02 01:42:29

问题


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

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