Python 类型错误 Unhashable type:set
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23577724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type error Unhashable type:set
提问by user2014111
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
回答by Amber
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 - e.g. frozenset
s.
相反,您需要将不可变对象放入一个集合中——例如frozenset
s。
If you change the return statement from your enum
method to...
如果您将方法中的 return 语句更改enum
为...
return [frozenset(i) for i in L]
...then it should work.
...然后它应该工作。
回答by Kiwi
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})}