简体   繁体   English

类型错误Unhashable type:set

[英]Type error Unhashable type:set

The below code has an error in function U=set(p.enum()) which a type error of unhashable type : 'set' actually if you can see the class method enum am returning 'L' which is list of sets and the U in function should be a set so can you please help me to resolve the issue or How can I convert list of sets to set of sets? 下面的代码在函数U = set(p.enum())中有一个错误,该错误是无法散列的类型的错误:'set',如果您可以看到类方法enum正在返回“ L”(它是集合的列表),函数中的U应该是一个集合,请您帮我解决这个问题,或者如何将集合列表转换为集合集?

class pattern(object):

        def __init__(self,node,sets,cnt):
            self.node=node
            self.sets=sets
            self.cnt=cnt

        def enum(self):
            L=[]
            if self.cnt==1:
                L = self.node
            else:
                for i in self.sets:
                    L=[]
                    for j in self.node:
                        if i!=j:
                            L.append(set([i])|set([j]))

            return L #List of sets              

    V=set([1,2,3,4])
    U=set()
    cnt=1
    for j in V:
        p=pattern(V,(U|set([j])),cnt)
        U=set(p.enum()) #type error Unhashable type:'set'   
        print U
            cnt+=1 

The individual items that you put into a set can't be mutable, because if they changed, the effective hash would change and thus the ability to check for inclusion would break down. 您放入集合中的各个项目是不可变的,因为如果它们发生变化,则有效哈希将发生变化,因此检查包含性的能力将被破坏。

Instead, you need to put immutable objects into a set - eg frozenset s. 取而代之的是,您需要将不可变的对象放入集合中-例如, frozenset

If you change the return statement from your enum method to... 如果将return语句从enum方法更改为...

return [frozenset(i) for i in L]

...then it should work. ...然后它应该工作。

This error is raised because a set can only contain immutable types. 因为集合只能包含不可变的类型,所以会引发此错误。 Or sets are mutable. 或集合是可变的。 However there is the frozenset type : 但是,有frozenset类型:

In [4]: a, b = {1,2,3}, {2,3,4}

In [5]: set([a,b])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-6ca6d80d679c> in <module>()
----> 1 set([a,b])

TypeError: unhashable type: 'set'

In [6]: a, b = frozenset({1,2,3}), frozenset({2,3,4})

In [7]: set([a,b])
Out[7]: {frozenset({1, 2, 3}), frozenset({2, 3, 4})}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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