簡體   English   中英

python 字典的奇怪行為

[英]Strange behavior with python dictionary

我正在學習 python hash function 並遇到以下行為。

>>> hash(-1)
-2
>>> hash(-2)
-2

SO 已經有一篇很棒的帖子回答了為什么: 為什么在 CPython 中 -1 和 -2 都是 hash 到 -2?

由於 python 字典使用鍵的 hash 來存儲值,因此預期以下 output 因為True1具有相同的 Z348040FC57283B4

>>> my_dict = { True: "true", 1: "one"}
>>> my_dict
{True: 'one'}
>>> hash(True)
1
>>> hash(1)
1

但如果我嘗試以下操作,我希望 output 為{ -1: "Minus Two"} ,因為-1-2具有相同的 hash。 但事實並非如此。

>>> my_dict = { -1: "Minus One", -2: "Minus Two"}
>>> my_dict
{-1: 'Minus One', -2: 'Minus Two'}
>>> hash(-1)
-2
>>> hash(-2)
-2

這種行為的原因是什么? 字典不使用密鑰的 hash 來存儲它的值嗎?

注意:我知道它是特定於 CPython 的,但我很想知道這種行為的原因。

它不僅檢查 object 的 hash 值,還檢查它的相等性。 您可以通過以下示例看到這一點:

>>> class Samesies:
...     def __hash__(self):
...             return 1
...     def __eq__(self, other):
...             return True
...
>>> {Samesies(): 1, Samesies(): 2}
{<__main__.Samesies object at 0x0000023997ACEFA0>: 2}

編輯: 1 == Truehash(1) == hash(True)的原因是bool實際上是int的子類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM