日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python中pop(),popitem()的整理

發(fā)布時間:2023/12/15 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中pop(),popitem()的整理 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在python中,列表,字典,有序字典的刪除操作有些凌亂,所以決定記錄下,以便以后用亂了。

列表:

列表刪除有三種方式:

l.pop()

l.remove()

del l[3:8]

已下面的code為例,見注釋:

l=['a','b','c','d','e','f','g','h','i','j','k',] l.pop()  #pop()不帶參數(shù),因為列表是有序的,刪除列表中最后一個元素 print(l)   l.pop(3)  #pop()入帶參數(shù),參數(shù)為列表中的索引號,刪除指定索引號的元素 print(l) l.remove('c')  #remove(),刪除列表中的對應(yīng)元素,必須帶參數(shù),參數(shù)為列表中的元素 print(l) del l[5]  #del 后面參數(shù)為list[index],索引也可為切片形式 print(l) del l[1:3] print(l) del l  #如果直接del本身,刪除被定義的變量 print(l)out: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] Traceback (most recent call last):File "/Users/shane/Desktop/中融騰更新文件/day3/test.py", line 55, in <module> ['a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j'] ['a', 'b', 'e', 'f', 'g', 'h', 'i', 'j'] ['a', 'b', 'e', 'f', 'g', 'i', 'j'] ['a', 'f', 'g', 'i', 'j']print(l) NameError: name 'l' is not defined [Finished in 0.1s with exit code 1]

字典:

字典中的刪除也有三個,pop(),popitem(),del

還是以例子說明吧:

d={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,} print(d) d.pop('d')  #刪除指定key以及key對應(yīng)的value,因為列表是無序的,所有必須有參數(shù),參數(shù)為列表中的指定key print(d) d.popitem()  #隨機刪除列表中的一條數(shù)據(jù),括號中無參數(shù) print(d) del d['c']  #刪除指定key,與pop相同,不同的是pop是圓括號,del是中括號,另外del可直接刪除變量 print(d)

結(jié)果:

{'b': 2, 'j': 10, 'i': 9, 'f': 6, 'c': 3, 'e': 5, 'g': 7, 'd': 4, 'a': 1, 'h': 8} {'b': 2, 'j': 10, 'i': 9, 'f': 6, 'c': 3, 'e': 5, 'g': 7, 'a': 1, 'h': 8} {'j': 10, 'i': 9, 'f': 6, 'c': 3, 'e': 5, 'g': 7, 'a': 1, 'h': 8} {'j': 10, 'i': 9, 'f': 6, 'e': 5, 'g': 7, 'a': 1, 'h': 8} [Finished in 0.1s]

有序字典:

OrderedDict 有序字典,是字典的擴展,繼承了字典的大部分功能。還是例子說明吧:

import collections od=collections.OrderedDict() od['xx']=23 od['ee']=21 od['ff']=33 od['aa']=11 od['bb']=22 print(od) od.pop('xx')  #刪除指定key,必須有參數(shù),參數(shù)是key print(od) od.popitem()  #因為有序字典是有序列的,所以popitem()刪除字典的最后一條數(shù)據(jù) print(od) del od['ee']  #同pop(),del 可刪除變量 print(od)OUT: OrderedDict([('xx', 23), ('ee', 21), ('ff', 33), ('aa', 11), ('bb', 22)]) OrderedDict([('ee', 21), ('ff', 33), ('aa', 11), ('bb', 22)]) OrderedDict([('ee', 21), ('ff', 33), ('aa', 11)]) OrderedDict([('ff', 33), ('aa', 11)])

做個總結(jié)圖吧:

總結(jié)

以上是生活随笔為你收集整理的python中pop(),popitem()的整理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。