python中pop()函數(shù)的語法與實例
語法:
列表 list.pop(obj=list[-1])
pop()用于刪除并返回列表中的一個元素(默認(rèn)為最后一個元素)
obj:要刪除并返回的列表元素
字典dict.pop(key[,default])
pop()用于刪除字典中給定的key及對應(yīng)的value,返回被刪除key對應(yīng)的value,key值必須給出。給定的key值不在字典中時,返回default值。
key:需要刪除的key值(不給出會報錯)
default:若沒有字典中key值,返回default值(給定的key值不在字典中時必須設(shè)置,否則會報錯)
實例:
列表
>>> list1 = [1,2,4,"hello","xy","你好"] >>> a = list1.pop()#默認(rèn)彈出最后一個元素 >>> print(a,list1) 你好 [1,2,4,"hello","xy"]
>>> list2 = [1,2,4,"hello","xy","你好"] >>> b = list2.pop(3)#彈出列表中第四個元素 >>> print(b,list2) hello [1,2,4,"xy","你好“]
字典
>>> dict1 = {"papa":"xy","sis":"nikki","dude":"cwy"}
>>> c = dict.pop()#不給定key值報錯
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
c = dict.pop()
TypeError: unbound method dict.pop() needs an argument
>>> dict1 = {"papa":"xy","sis":"nikki","dude":"cwy"}
>>> c = dict1.pop("papa")
>>> print(c,dict1)
xy {'sis': 'nikki', 'dude': 'cwy'}
>>> dict2 = {"papa":"xy","sis":"nikki","dude":"cwy"}
>>> d = dict2.pop("www")#給定鍵不在字典內(nèi)時,未設(shè)置default值報錯
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
d = dict2.pop("www")
KeyError: 'www'
>>> dict2 = {"papa":"xy","sis":"nikki","dude":"cwy"}
>>> d = dict2.pop("www","不在字典內(nèi)")
>>> print(d,dict2)
不在字典內(nèi) {'papa': 'xy', 'sis': 'nikki', 'dude': 'cwy'}
總結(jié)
到此這篇關(guān)于python中pop()函數(shù)語法與實例的文章就介紹到這了,更多相關(guān)python中pop()函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Win10系統(tǒng)下安裝編輯器之神(The?God?of?Editor)Vim并且構(gòu)建Python生態(tài)開發(fā)環(huán)境過程(2
這篇文章主要介紹了Win10系統(tǒng)下安裝編輯器之神(The?God?of?Editor)Vim并且構(gòu)建Python生態(tài)開發(fā)環(huán)境(2020年最新攻略),本次我們在Win10平臺構(gòu)建一套以Vim為核心的Python開發(fā)環(huán)境,需要的朋友可以參考下2023-01-01
Python使用DPKT實現(xiàn)分析數(shù)據(jù)包
dpkt項目是一個Python模塊,主要用于對網(wǎng)絡(luò)數(shù)據(jù)包進(jìn)行解析和操作,z這篇文章主要為大家介紹了python如何利用DPKT實現(xiàn)分析數(shù)據(jù)包,有需要的可以參考下2023-10-10
PyCharm中Matplotlib繪圖不能顯示UI效果的問題解決
這篇文章主要介紹了PyCharm中Matplotlib繪圖不能顯示UI效果的問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03

