1 回答

TA貢獻1828條經驗 獲得超3個贊
Python 中的類型是where equals the number和equals the numberbool的子類型:intTrue1False0
>>> True == 1
True
>>> False == 0
True
當這些值被散列時,它們也會產生相同的值:
>>> hash(True)
1
>>> hash(1)
1
>>> hash(False)
0
>>> hash(0)
0
現在,由于字典鍵基于哈希和對象相等(首先使用哈希相等來快速找到可能相等的鍵,然后通過相等進行比較),因此產生相同哈希且相等的兩個值將產生相同的值字典中的“槽”。
如果您創建也具有此行為的自定義類型,您也可以看到這一點:
>>> class CustomTrue:
def __hash__(self):
return 1
def __eq__(self, other):
return other == 1
>>> pairs = {
1: "apple",
"orange": [2, 3, 4],
True: False,
None: "True",
}
>>> pairs[CustomTrue()] = 'CustomTrue overwrites the value'
>>> pairs
{1: 'CustomTrue overwrites the value', 'orange': [2, 3, 4], None: 'True'}
雖然這解釋了這種行為,但我確實同意它可能有點令人困惑。因此,我建議不要使用不同類型的字典鍵,以免遇到這種情況。
添加回答
舉報