语法:

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

总结

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com