圆月山庄资源网 Design By www.vgjia.com

语法:

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

总结

标签:
python中pop函数的用法,python中pop怎么用,Python列表pop

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com