蟒蛇字典难题

编程入门 行业动态 更新时间:2024-10-06 08:26:05
本文介绍了蟒蛇字典难题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我输入的控制台中

>>> 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

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.

更多推荐

蟒蛇字典难题

本文发布于:2023-11-29 15:15:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646763.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:蟒蛇   字典   难题

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!