Posted in Python onDecember 01, 2020
语法:
列表 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()函数的语法与实例
- Author -
awen_5声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@