亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

淺談Python的字典鍵名可以是哪些類型

 更新時(shí)間:2021年09月02日 10:41:20   作者:張欣-男  
本文主要介紹了Python的字典鍵名可以是哪些類型,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

今天看別人代碼時(shí)發(fā)現(xiàn)一個(gè)事,就是把對(duì)象當(dāng)作字典的鍵名,并且把兩個(gè)對(duì)象(類的實(shí)例)當(dāng)作鍵名,然后去查了下:

鍵必須是不可變的,如字符串,數(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 多個(gè)對(duì)象可當(dāng)作鍵名,順序不同時(shí)是不同的鍵

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)除了列表不能當(dāng)作鍵名,其它都 可以,還可以放多個(gè)。
(2)我是這樣理解的,列表是可變的,其他類型都是不可變的。對(duì)象作為鍵名時(shí),實(shí)際傳入的是對(duì)象的地址,也是不可變的。
(3)放多個(gè)時(shí)不同順序時(shí)鍵不同。

------2020.04.07更新-----
感謝兩次網(wǎng)友的提醒。
(1)準(zhǔn)確的說是列表、字典這種不可哈希(unhashable)的類型不可當(dāng)做鍵值,可哈希的類型才可當(dāng)作鍵。

到此這篇關(guān)于淺談Python的字典鍵名可以是哪些類型的文章就介紹到這了,更多相關(guān)Python 字典鍵名 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論