Python中的新手,帮助。为什么我收到此错误:“TypeError:列表索引必须是整数,而不是元组”
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
Python中的新手,帮助。为什么我收到此错误:“TypeError:列表索引必须是整数,而不是元组”
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
这个语法是错误的:
imheight[i,j] = hij
imheight[j,i] = hij
也许你是这个意思?
imheight[i][j] = hij
imheight[j][i] = hij
但话又说回来,imheight
是一个一维列表,但你假设它是一个二维矩阵。只有在您第一次正确初始化时它才会起作用imheight
:
imheight = [[0] * len(tables) for _ in range(len(tables))]
字典将为您提供所需的分配行为:
imheight = {}
但是,如果您以后需要以某种顺序对其进行迭代,这将不像您将其作为正确的列表列表那样简单,因为字典不保持顺序。但是,这可能工作得很好。
不是
imheight[i,j] = hij
它应该这样写:
imheight[i:j] = hij
它表示从 i 到 j 的索引。