Python:字典的pop()方法


pop():移除序列中的一個元素(默認最后一個元素),並且返回該元素的值。

一)移除list的元素,若元素序號超出list,報錯:pop index out of range(超出范圍的流行指數);

 

A、默認移除最后一個元素

list_1 = [1, 2, 3, 4, 5]

a = list_1.pop()

print (list_1, a)

-->[1, 2, 3, 4] 5

 

B、移除list中的某一個元素:pop(元素序號)

list_1 = [1, 2, 3, 4, 5]

a = list_1.pop(2)

print (list_1, a)

-->[1, 2, 4, 5] 3

 

二)移除dict中的元素(只能移除1個元素):pop(),()內不能為空,要有key;若key不在dict內,需要主動給出需要返回的數據,否則報錯;

 

A、key在dict_1內

dict_1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}

a = dict_1.pop(2)

print(dict_1,   a)

-->{1:'a', 3:'c', 4:'d', 5:'e'}  b

 

B、key不在dict_1內:返回pop給定的數據

dict_1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}

a = dict_1.pop(6,  [1, 2, 3, 4])

print(dict_1,   a)

-->{1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}  [1, 2, 3, 4]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM