如果这有帮助...如果您出于某种原因确实需要将不可散列的东西转换为可散列的等价物,您可能会这样做:
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
我的 HashableDict 实现是来自here 的最简单和最不严格的示例。如果您需要支持酸洗和其他功能的更高级的 HashableDict,请检查许多其他实现。在我上面的版本中,我想保留原始的 dict 类,从而保留 OrderedDicts 的顺序。我还使用 here 的 AttrDict 进行类似属性的访问。
我上面的例子没有任何权威性,只是我对一个类似问题的解决方案,我需要将一些东西存储在一个集合中并需要先“散列”它们。