[英]Python Unhashable Type Error
Currently I am creating a function called randomwalk
that takes as input the set edges
, a teleport probability a
and a positive integer iters
and performs the random walk. 目前,我创建一个函数调用
randomwalk
是作为输入设定的edges
,一个瞬移概率a
和一个正整数iters
并进行随机游走。
Starting from any page, the function will randomly follow links from one page to the next, teleporting to a completely random page with probability a
at each iteration. 从任何页面开始,该函数将随机跟随从一页到下一页的链接,并在每次迭代时以概率
a
传送到完全随机的页面。
It should also store all visited states and eventually create a histogram of the frequency by which each page was visited. 它还应该存储所有访问过的状态,并最终创建访问每个页面的频率的直方图。 This histogram is what the randomwalk function will return
该直方图是randomwalk函数将返回的结果
This is what I have so far, I'm getting an Unhashable Type error though for list. 到目前为止,这就是我的清单,但是出现了Unhashable Type错误。 Here is the list of edges
这是边的列表
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))
How would I fix this? 我该如何解决?
The reason why you are getting this error is that you cannot use list
as a key in dict
in python. 出现此错误的原因是,您无法在Python中将
list
用作dict
中的键。 Use tuple
instead: 使用
tuple
代替:
error_dict = {[1, 2]: "some_data"}
# >>> TypeError: unhashable type: 'list'
correct_dict = {(1, 2): "some_data"}
# no error
The error in you code comes from this line: 您代码中的错误来自以下行:
pages = list({edges[0] for edge in edges})
You probably made a mistake in edges[0]
, change it to edge[0]
: 您可能在
edges[0]
犯了一个错误,将其更改为edge[0]
:
pages = list({edge[0] for edge in edges})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.