IndexError:列表索引超出范围(它必须是字典,而不是列表)

时间:2014-08-28 14:51:56

标签: python

EX_GRAPH1 = {0:[1,4,5],
         1:[2,6],
         2:[3],
         3:[0],
         4:[1],
         5:[2],
         6:[]
         }

此函数采用有向图有向图 (表示为字典)并计算 图中节点的in-degrees。

def compute_in_degrees(digraph):
in_degrees = {}
i = 0
j = 0
matches = []
while i < len(digraph):
    m = 0
    while j < len(digraph):
        if digraph[i][j] == i: <--- HERE IndexError: list index out of range
            j += 1
            m += 1
            matches.append(m)
        else:
            j += 1
    in_degrees[i] = matches
    i += 1
return in_degrees
print compute_in_degrees(EX_GRAPH1)

请帮助

2 个答案:

答案 0 :(得分:0)

尝试:

while j < len(digraph[i]):

目前,您只是重复i的循环,因此您可能会超支。或者,正如@jonrsharpe在评论中所说,使用for循环:

def compute_in_degrees(digraph):
    in_degrees = {}
    i = 0
    j = 0
    matches = []
    for i, sublist in enumerate(digraph):
        m = 0
        for j in sublist:
            if j == i:
                m += 1
                matches.append(m)
        in_degrees[i] = matches
    return in_degrees
print compute_in_degrees(EX_GRAPH1)

答案 1 :(得分:0)

您正在迭代i x j条目但digraph(传入EX_GRAPH1)不是2D数组,它是稀疏数组。< / p>

有些条目的长度为0,1,2,3个条目。

不要使用dict。考虑numpy和/或networkx