我在生成字典时遇到此错误。我有三份清单。以下是打印
edge
[(6.0, 4.0), (4.0, 3.0), (4.0, 5.0), (3.0, 2.0), (5.0, 2.0), (5.0, 1.0), (2.0, 1.0)]
weight
[3, 5, 8, 0, 16, 2, 8]
node
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
我的代码
GraphDict = {}
for i in range(len(node)):
print('node',node[i])
GraphDict[node[i]] = []
for k in range(len(edge)):
if node[i] == edge[k][0]:
GraphDict[node[i]][edge[k][1]] = weight[k]
print('Edge: n1, n2: weights', GraphDict[node[i]])
print('Dictionary Print')
print(GraphDict)
行中出现错误。错误:列表索引必须是整数,而不是浮点
GraphDict[node[i]][edge[k][1]] = weight[k]
当我将所有浮点转换为整数时,错误是"IndexError:listassignmentindexoutrange"
GraphDict = {}
for i in range(len(node)):
print('node',node[i])
GraphDict[node[i]] = []
for k in range(len(edge)):
if node[i] == edge[k][0]:
print(int(node[i]))
ni = int(node[i])
print(int(edge[k][1]))
ei = int(edge[k][1])
print(weight[k])
GraphDict[ni][ei] = weight[k]
print('Edge: n1, n2: weights', GraphDict[node[i]])
print('Dictionary Print')
print(GraphDict)
错误消息说明了一切:"列表索引必须是整数,而不是浮点"。因此,请确保将node[i]
转换为int
,或者在一开始就存储整数:
GraphDict[int(node[i])]
或
node = [1, 2, 3, 4, 5, 6]
edge
也是如此。