Python 无法散列的类型错误

Python Unhashable Type Error

目前我正在创建一个名为 randomwalk 的函数,它将集合 edges、传送概率 a 和正整数 iters 作为输入并执行随机走。

从任何页面开始,该函数将随机跟踪从一个页面到下一个页面的链接,并在每次迭代时以 a 的概率传送到一个完全随机的页面。

它还应该存储所有访问过的状态,并最终创建每个页面访问频率的直方图。这个直方图就是随机游走函数 return

这就是我目前所拥有的,但我收到了一个无法散列的类型错误,尽管对于列表。这是边缘列表

edges =[[0,1], [1,1], [2,0], [2,2], [2,3], [3,3], [3,4], [4,6], [5,5], [6,6], [6,3]]

def randomWalk(edges, a ,iters):
    pages = {edge[0] for edge in edges}
    dict_edges = {}
    for edge_from, edge_to in edges:
        if edge_from not in dict_edges:
            dict_edges[edge_from] = [edge_to]
        else:
            dict_edges[edge_from].append(edge_to)
    current_page = random.choice(pages)
    visit_counts_dictionary = {page:0 for page in pages}
    visit_counts_dictionary[current_page] +=1
    for _ in range(iters):
        if random.uniform(0,1) < a:
            current_page = random.choice(pages)
            visit_counts_dictionary[current_page] += 1
        else:
            current_page = random.choice(dict_edges[current_page])
            visit_counts_dictionary[current_page] += 1
    print visit_counts_dictionary

print(randomWalk(edges, 0, 10))

我该如何解决这个问题?

您收到此错误的原因是您不能在 python 中使用 list 作为 dict 中的键。使用 tuple 代替:

error_dict = {[1, 2]: "some_data"}
# >>> TypeError: unhashable type: 'list'

correct_dict = {(1, 2): "some_data"}
# no error

您代码中的错误来自这一行:

pages = list({edges[0] for edge in edges})

您可能在edges[0]中输入错误,将其更改为edge[0]:

pages = list({edge[0] for edge in edges})