列表 list.pop(obj=list[-1])

pop()用来简略并归来列表中的一个元素(默许为结果一个元素)

obj:要简略并归来的列表元素

字典dict.pop(key[,default])

pop()用来简略字典中给定的key及对应的value,归来被简略key对应的value,key值必需给出。给定的key值不在字典中时,归来default值。

key:须要简略的key值(不给出会报错)

default:若没有字典中key值,归来default值(给定的key值不在字典中时必需树立,要不会报错)

范例:

列表

>>> list1 = [1,2,4,"hello","xy","您好"]

>>> a = list1.pop()#默许弹出结果一个元素

>>> 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")#给定键不在字典内时,未树立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","不在字典内")

>>> print(d,dict2)

不在字典内 {'papa': 'xy', 'sis': 'nikki', 'dude': 'cwy'}