淺談Python的字典鍵名可以是哪些類(lèi)型
今天看別人代碼時(shí)發(fā)現(xiàn)一個(gè)事,就是把對(duì)象當(dāng)作字典的鍵名,并且把兩個(gè)對(duì)象(類(lèi)的實(shí)例)當(dāng)作鍵名,然后去查了下:
鍵必須是不可變的,如字符串,數(shù)字或元組。
1 鍵的類(lèi)型,列表/字典不可以,其它都可以但是網(wǎng)上卻沒(méi)有說(shuō)其他類(lèi)型可不可以,怎么用的。我寫(xiě)代碼試了下:
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 多個(gè)對(duì)象可當(dāng)作鍵名,順序不同時(shí)是不同的鍵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)作鍵名,其它都 可以,還可以放多個(gè)。(2)我是這樣理解的,列表是可變的,其他類(lèi)型都是不可變的。對(duì)象作為鍵名時(shí),實(shí)際傳入的是對(duì)象的地址,也是不可變的。(3)放多個(gè)時(shí)不同順序時(shí)鍵不同。
------2020.04.07更新-----感謝兩次網(wǎng)友的提醒。(1)準(zhǔn)確的說(shuō)是列表、字典這種不可哈希(unhashable)的類(lèi)型不可當(dāng)做鍵值,可哈希的類(lèi)型才可當(dāng)作鍵。
到此這篇關(guān)于淺談Python的字典鍵名可以是哪些類(lèi)型的文章就介紹到這了,更多相關(guān)Python 字典鍵名 內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 原生js實(shí)現(xiàn)的觀察者和訂閱者模式簡(jiǎn)單示例2. asp讀取xml文件和記數(shù)3. JS錯(cuò)誤處理與調(diào)試操作實(shí)例分析4. JS實(shí)現(xiàn)表單中點(diǎn)擊小眼睛顯示隱藏密碼框中的密碼5. python基于scrapy爬取京東筆記本電腦數(shù)據(jù)并進(jìn)行簡(jiǎn)單處理和分析6. Python ellipsis 的用法詳解7. 在終端啟動(dòng)Python時(shí)報(bào)錯(cuò)的解決方案8. Python如何實(shí)現(xiàn)感知器的邏輯電路9. 基于android studio的layout的xml文件的創(chuàng)建方式10. PHP實(shí)現(xiàn)基本留言板功能原理與步驟詳解
