TypeError : Unhashable type

前端 未结 6 686
灰色年华
灰色年华 2020-11-29 05:45

I am trying to get a list of list of tuples : something like [ [(1,0),(2,0),(3,0)],[(1,1),(2,1),(3,1)....]] I used this statement

set([(a,b)for         


        
6条回答
  •  Happy的楠姐
    2020-11-29 06:27

    You are creating a set via set(...) call, and set needs hashable items. You can't have set of lists. Because list's arent hashable.

    [[(a,b) for a in range(3)] for b in range(3)] is a list. It's not a hashable type. The __hash__ you saw in dir(...) isn't a method, it's just None.

    A list comprehension returns a list, you don't need to explicitly use list there, just use:

    >>> [[(a,b) for a in range(3)] for b in range(3)]
    [[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]
    

    Try those:

    >>> a = {1, 2, 3}
    >>> b= [1, 2, 3]
    >>> type(a)
    
    >>> type(b)
    
    >>> {1, 2, []}
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'list'
    >>> print([].__hash__)
    None
    >>> [[],[],[]] #list of lists
    [[], [], []]
    >>> {[], [], []} #set of lists
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'list'
    

提交回复
热议问题