Python不可损坏类型E

2024-04-29 12:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

它还应该存储所有访问的状态,并最终创建一个访问每个页面的频率直方图。这个直方图就是randomwalk函数将返回的结果

这是我到目前为止,我得到了一个不可修复的类型错误,虽然列表。这是边的列表

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))

我该怎么解决这个问题?你知道吗


Tags: 函数infromfordictionarypagerandom页面
1条回答
网友
1楼 · 发布于 2024-04-29 12:09:21

出现此错误的原因是在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})

相关问题 更多 >