Unable to convert list into set, raises “unhashable type: 'list' ” error

前端 未结 2 965
深忆病人
深忆病人 2021-01-13 16:44

So I\'m trying to find all sub-lists of a list and here is what I have now. I\'m new to Python and I don\'t understand why \" Q3_ans=set(ans)\" raises an error. I\'ve tried

2条回答
  •  爱一瞬间的悲伤
    2021-01-13 17:28

    As you can figure out why, mutable types like lists can't be hashable, so can't be converted to a set. You can try returning tuple instead; an immutable counterpart for list:

    def f2(seq):
        assert len(seq)==2
        assert isinstance(x, tuple) # what's `x` actually?
        a, b = seq
        return ((a), (b), (a,b))
    
    def all_sublists(x):
        assert isinstance(x, list)
        ans = []
        for i in range(0, len(x) - 1):
            for j in range(1, len(x)):
                temp = (x[i], x[j])
                temp = [f2(temp)]
                ans.extend(temp)
        Q3_ans = set(tuple(ans))
        return Q3_ans
    

    then

    all_sublists([1, 2, 3])
    

    You can read more about tuple type in the documentation.

提交回复
热议问题