简体   繁体   中英

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.

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.

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

This is what I have so far, I'm getting an Unhashable Type error though for list. 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. Use tuple instead:

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] :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM