我偶然发现了一篇博文,详细介绍了如何在Python中实现powerset函数.所以我开始尝试自己的方式,并发现Python显然不能有一组集合,因为set不可清除.这是令人厌烦的,因为powerset的定义是它是一组集合,我想使用实际的集合操作来实现它.
>>> set([ set() ])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
Run Code Online (Sandbox Code Playgroud)
有没有一个很好的理由Python设置不可用?
Sve*_*ach 105
通常,只有不可变对象在Python中可以使用.set()- frozenset()- 的不可变变体是可以清除的.
Joh*_*Jr. 16
从Python文档:
hashable
如果对象具有在其生命周期内永远不会更改的哈希值(它需要hash()方法),并且可以与其他对象进行比较(它需要 eq()或cmp()方法),则该对象是可哈希的 .比较相等的可哈希对象必须具有相同的哈希值.Hashability使对象可用作字典键和set成员,因为这些数据结构在内部使用哈希值.
所有Python的不可变内置对象都是可清除的,而没有可变容器(例如列表或字典).默认情况下,作为用户定义类实例的对象是可清除的; 他们都比较不相等,他们的哈希值是他们的id().
如果这有帮助...如果你真的需要将不可用的东西转换为可出售的等价物,出于某种原因你可能会这样做:
from collections import Hashable, MutableSet, MutableSequence, MutableMapping
def make_hashdict(value):
"""
Inspired by https://stackoverflow.com/questions/1151658/python-hashable-dicts
- with the added bonus that it inherits from the dict type of value
so OrderedDict's maintain their order and other subclasses of dict() maintain their attributes
"""
map_type = type(value)
class HashableDict(map_type):
def __init__(self, *args, **kwargs):
super(HashableDict, self).__init__(*args, **kwargs)
def __hash__(self):
return hash(tuple(sorted(self.items())))
hashDict = HashableDict(value)
return hashDict
def make_hashable(value):
if not isinstance(value, Hashable):
if isinstance(value, MutableSet):
value = frozenset(value)
elif isinstance(value, MutableSequence):
value = tuple(value)
elif isinstance(value, MutableMapping):
value = make_hashdict(value)
return value
my_set = set()
my_set.add(make_hashable(['a', 'list']))
my_set.add(make_hashable({'a': 1, 'dict': 2}))
my_set.add(make_hashable({'a', 'new', 'set'}))
print my_set
Run Code Online (Sandbox Code Playgroud)
我HashableDict实现从最简单和最严谨的例子在这里.如果您需要更高级的HashableDict来支持酸洗和其他东西,请检查许多其他实现.在我上面的版本中,我想保留原始的dict类,从而保留OrderedDicts的顺序.我也从这里使用AttrDict 进行类似属性的访问.
我上面的例子并不具有权威性,只是我对类似问题的解决方案,我需要将一些东西存储在一个集合中,并且需要先将它们"哈希化".