淺談Python的字典鍵名可以是哪些類型
今天看別人代碼時發(fā)現(xiàn)一個事,就是把對象當作字典的鍵名,并且把兩個對象(類的實例)當作鍵名,然后去查了下:
鍵必須是不可變的,如字符串,數(shù)字或元組。
1 鍵的類型,列表/字典不可以,其它都可以
但是網(wǎng)上卻沒有說其他類型可不可以,怎么用的。我寫代碼試了下:
class Person: def __init__(self, name): self.name = name i = 5 s = 'abc' t = (5,'a') p = Person('Lily') q = Person('xiao') m = {'a':1, 'b':10} lst = [1,2,3] d = {} d[i] = 'five' d[s] = 'ABC' d[t] = 'five-a' d[p] = 'name:Lily' # d[lst] = 'list : 1,2,3' # TypeError: unhashable type: 'list' d[p, q] = 'two people: Lily and xiao' d[i,s,t,p,q] = 'all in key' for k, v in d.items(): print(k, '=>', v)
輸出結(jié)果:
5 => five
abc => ABC
(5, 'a') => five-a
<__main__.Person object at 0x000001803EEF27F0> => name:Lily
(<__main__.Person object at 0x000001803EEF27F0>, <__main__.Person object at 0x000001803EEF28D0>) => two people: Lily and xiao
(5, 'abc', (5, 'a'), <__main__.Person object at 0x000001803EEF27F0>, <__main__.Person object at 0x000001803EEF28D0>) => all in key
2 多個對象可當作鍵名,順序不同時是不同的鍵
print(d[p, q]) print(d[q, p])
輸出:
two people: Lily and xiao
Traceback (most recent call last):File "<ipython-input-15-12aff481ab93>", line 1, in <module>
runfile('C:/Users/Xpeng/.spyder-py3/temp.py', wdir='C:/Users/Xpeng/.spyder-py3')File "D:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)File "D:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)File "C:/Users/Xpeng/.spyder-py3/temp.py", line 37, in <module>
print(d[q, p])KeyError: (<__main__.Person object at 0x000001803EF58940>, <__main__.Person object at 0x000001803EF58668>)
3 結(jié)論【有誤】:
(1)除了列表不能當作鍵名,其它都 可以,還可以放多個。
(2)我是這樣理解的,列表是可變的,其他類型都是不可變的。對象作為鍵名時,實際傳入的是對象的地址,也是不可變的。
(3)放多個時不同順序時鍵不同。
------2020.04.07更新-----
感謝兩次網(wǎng)友的提醒。
(1)準確的說是列表、字典這種不可哈希(unhashable)的類型不可當做鍵值,可哈希的類型才可當作鍵。
到此這篇關(guān)于淺談Python的字典鍵名可以是哪些類型的文章就介紹到這了,更多相關(guān)Python 字典鍵名 內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。