淺談Python的字典鍵名可以是哪些類型
今天看別人代碼時發(fā)現(xiàn)一個事,就是把對象當(dāng)作字典的鍵名,并且把兩個對象(類的實例)當(dāng)作鍵名,然后去查了下:
鍵必須是不可變的,如字符串,數(shù)字或元組。
1 鍵的類型,列表/字典不可以,其它都可以但是網(wǎng)上卻沒有說其他類型可不可以,怎么用的。我寫代碼試了下:
class Person: def __init__(self, name):self.name = namei = 5s = ’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 => fiveabc => 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 多個對象可當(dāng)作鍵名,順序不同時是不同的鍵print(d[p, q])print(d[q, p])
輸出:
two people: Lily and xiaoTraceback (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 StudioSharedAnaconda3_64libsite-packagesspyderutilssitesitecustomize.py', line 705, in runfile execfile(filename, namespace)
File 'D:Program Files (x86)Microsoft Visual StudioSharedAnaconda3_64libsite-packagesspyderutilssitesitecustomize.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)除了列表不能當(dāng)作鍵名,其它都 可以,還可以放多個。(2)我是這樣理解的,列表是可變的,其他類型都是不可變的。對象作為鍵名時,實際傳入的是對象的地址,也是不可變的。(3)放多個時不同順序時鍵不同。
------2020.04.07更新-----感謝兩次網(wǎng)友的提醒。(1)準確的說是列表、字典這種不可哈希(unhashable)的類型不可當(dāng)做鍵值,可哈希的類型才可當(dāng)作鍵。
到此這篇關(guān)于淺談Python的字典鍵名可以是哪些類型的文章就介紹到這了,更多相關(guān)Python 字典鍵名 內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 在Android中使用WebSocket實現(xiàn)消息通信的方法詳解2. 淺談python出錯時traceback的解讀3. Python importlib動態(tài)導(dǎo)入模塊實現(xiàn)代碼4. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解5. windows服務(wù)器使用IIS時thinkphp搜索中文無效問題6. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向7. Nginx+php配置文件及原理解析8. 利用promise及參數(shù)解構(gòu)封裝ajax請求的方法9. .NET中l(wèi)ambda表達式合并問題及解決方法10. JSP數(shù)據(jù)交互實現(xiàn)過程解析
