今天我為大家講解python中pop函數的使用。#python#
簡介——
pop()函數是python解釋器的內置方法,可作用於列表,字典。pop為「彈出」之意。
用法說明——
在builtins.py中找到pop函數。
列表:
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
移出並返回L中索引的值,在L為空或超出索引時拋出錯誤。
字典:
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
指定key移出並返回特定的value,在key找不到或已經返回時拋出key錯誤。
測試——
測試1:
list=[1,2,3,4]
object0=list.pop()
object1=list.pop(0)
#此時list.pop(3)報錯
print(object0)
print(object1)
print(list)
運行結果:4 1 [2,3]
結論:返回pop刪除的值並賦值給對象,原列表改變。pop()默認為最後一個元素,即pop(-1),pop(index)指定索引。
測試2:
list=[1,2,3,4]
object2=list.pop(0,2)
print(list)
print(object2)
運行報錯。
結論:pop(index)索引只能是一個數值
測試3:
dict={'a':1,'b':2,'c':3}
object3=dict.pop('b')
print(object3)
print(dict)
運行結果:2 {'a':1,'c':3}
結論:pop作用於字典,需要指定key值,返回刪除的value。
應用——
例:遊戲中,你有一個背包,然後你殺死了『兔子1』得到了『肉』,肉存到了背包中,地圖上少了一隻兔子。
bag=[]
map={'兔子1':'肉'}
bonus=dict.pop('兔子1')
bag.append(bonus)
拓展popitem——
字典:
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
移出並返回D隨機的鍵值對作為一個兩元素元組,在D為空時拋出key錯誤。
喜歡python的小夥伴關注我吧