[英]Python Unhashable Type Error
目前,我创建一个函数调用randomwalk
是作为输入设定的edges
,一个瞬移概率a
和一个正整数iters
并进行随机游走。
从任何页面开始,该函数将随机跟随从一页到下一页的链接,并在每次迭代时以概率a
传送到完全随机的页面。
它还应该存储所有访问过的状态,并最终创建访问每个页面的频率的直方图。 该直方图是randomwalk函数将返回的结果
到目前为止,这就是我的清单,但是出现了Unhashable Type错误。 这是边的列表
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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.