当前位置:首页 >> 脚本专栏

python中pop()函数的语法与实例

语法:

列表 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'}

总结