" list indices必须是整数,而不是float" /" IndexError:列表分配索引超出范围"字典中的错误

时间:2015-11-28 09:36:21

标签: python dictionary

生成字典时出现此错误。我有三个清单。以下是打印

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:列表赋值索引超出范围"

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)

1 个答案:

答案 0 :(得分:0)

错误消息说明了一切:“列表索引必须是整数,而不是浮点数”。因此,请务必将dateLabel2转换为node[i]或在一开始就存储整数:

int

GraphDict[int(node[i])]

同样适用于node = [1, 2, 3, 4, 5, 6]