本文介绍了蟒蛇字典难题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我输入的控制台中

>>> class S(str): pass
...
>>> a = 'hello'
>>> b = S('hello')
>>> d = {a:a, b:b}
>>> d
{'hello': 'hello'}
>>> type(d[a])
<class '__main__.S'>
>>> type(d[b])
<class '__main__.S'>

我以为先是认为 d hash(a) hash(b)返回相同的值,所以我试过:

I thought at first that the reason that d only kept one pair was because hash(a) and hash(b) returned the same values, so I tried:

>>> class A(object):
...     def __hash__(self):
...             return 0
...
>>> class B(object):
...     def __hash__(self):
...             return 0
...
>>> d = {A():A(),B():B()}
>>> d
{<__main__.A object at 0x101808b90>: <__main__.A object at 0x101808b10>, <__main__.B object at 0x101808d10>: <__main__.B object at 0x101808cd0>}

现在我很困惑
如何进入第一个代码列表, d 只保留一对,但在第二个列表中 d 尽管有相同的哈希值,但是两个密钥都被保留了。

Now I'm confused.How come in the first code listing, d only kept one pair, but in the second listing d both keys were kept despite having same hash?

推荐答案

原始示例中的两个对象被折叠不是因为它们具有相同的哈希,但是因为他们比较平等。相对于等级而言,密钥是唯一的,而不是哈希。 Python要求比较相等的任何两个对象必须具有相同的哈希值(但不一定相反)。

The two objects in your original example were collapsed not because they have the same hash, but because they compare equal. Dict keys are unique with respect to equality, not hash. Python requires that any two objects that compare equal must have the same hash (but not necessarily the reverse).

在第一个示例中,两个对象相等,因为它们两者都有 str 平等行为。由于两个对象的比较相等,它们被折叠为一个。在第二个例子中,它们不相等。默认情况下,用户定义的类使用相同的身份标识 - 即每个对象的比较仅等于自身。所以你的两个对象不相等。没有关系,他们有相同的哈希。

In your first example, the two objects are equal, since they both have the str equality behavior. Since the two objects compare equal, they are collapsed to one. In the second example, they don't compare equal. By default user-defined classes use identity for equality --- that is, each object compares equal only to itself. So your two objects are not equal. It doesn't matter than they have the same hash.

这篇关于蟒蛇字典难题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:06