作者:tcystars_628 | 来源:互联网 | 2023-02-10 15:42
1> Moses Koledo..:
您可以使用frozenset
而不是元组:
>>> hash(frozenset([1, 2, 'a', 'b']))
1190978740469805404
>>>
>>> hash(frozenset([1, 'a', 2, 'b']))
1190978740469805404
>>>
>>> hash(frozenset(['a', 2, 'b', 1]))
1190978740469805404
但是,从迭代中删除重复项会产生一个微妙的问题:
>>> hash(frozenset([1,2,1])) == hash(frozenset([1,2,2]))
True
您可以通过使用迭代创建一个计数器collections.Counter
并调用frozenset
计数器的项来解决这个问题,从而保留原始iterable中每个项的计数:
>>> from collections import Counter
>>>
>>> hash(frozenset(Counter([1,2,1]).items()))
-307001354391131208
>>> hash(frozenset(Counter([1,1,2]).items()))
-307001354391131208
>>>
>>> hash(frozenset(Counter([1,2,1]).items())) == hash(frozenset(Counter([1,2,2]).items()))
False