Python 设置 1 和 True 的重复 [英] Python set interpetation of 1 and True
问题描述
在 IPython 3 交互式 shell 中:
In IPython 3 interactive shell:
In [53]: set2 = {1, 2, True, "hello"}
In [54]: len(set2)
Out[54]: 3
In [55]: set2
Out[55]: {'hello', True, 2}
这是不是因为 1 和 True 得到相同的解释,所以鉴于该集合消除了重复项,只有其中一个(True)可以保留?我们如何才能同时保留两者?
Is that because 1 and True get the same interpetation so given that set eliminates duplicates, only one of them (True) gets to stay? How can we keep both?
推荐答案
集合是 哈希.即使语句 1 is True
是 False,语句 1 == True
也是 True.因此,它们具有相同的哈希值并且不能单独存在于一个集合中,并且您不能将它们都保存在一个集合中
A set is a collection of hashables. Even though the statement 1 is True
is False, the statement 1 == True
is True. Because of that, they have the same hash value and cannot exist separately in a set, and you cannot keep them both in a set
EDIT 明确地说,正如 jme 所指出的,这是因为两件事都是正确的 - 它们是相等的(根据 __eq__
)并且它们具有相同的 __hash__
).
EDIT To make it explicit, as jme pointed out, it is because BOTH things are true - they are equal (per __eq__
) AND they have the same hash value (per __hash__
).
在一个完美的世界中,相等的对象也将具有相同的哈希值,幸运的是,对于内置类型也是如此.
In a perfect world, equal objects would also have the same hash value, and thankfully this is true for built-in types.
这篇关于Python 设置 1 和 True 的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!