Python列表pop()函數(shù)使用實(shí)例詳解
pop() 可以「刪除」列表中的元素(默認(rèn)最后一個(gè))。
語法
list.pop( index )
參數(shù)
- index :(可選)需要?jiǎng)h除的元素的索引值
返回值
- 返回被刪除的元素
實(shí)例:刪除列表中第一個(gè)元素
list1 = [1, 2, 3] list1.pop(1) print(list1)
輸出:
[1, 3]
1、按照索引刪除元素
pop() 可以根據(jù)指定的「索引」,刪除對(duì)應(yīng)「位置」的元素。
1.1、正數(shù)索引
索引為「正數(shù)」時(shí),從 0 開始,按照從左往右的順序刪除
list1 = [1, 2, 3, 4] print('刪除前:', list1) list1.pop(0) print('刪除后:', list1)
輸出:
刪除前: [1, 2, 3, 4]
刪除后: [2, 3, 4]
指定的索引不能超過列表的「長(zhǎng)度」,否則會(huì)報(bào)錯(cuò) IndexError: pop index out of range
1.2、負(fù)數(shù)索引
索引為「負(fù)數(shù)」時(shí),從 1 開始,按照從右往左的順序刪除
list1 = [1, 2, 3, 4] print('刪除前:', list1) list1.pop(-1) print('刪除后:', list1)
輸出:
刪除前: [1, 2, 3, 4]
刪除后: [1, 2, 3]
索引超過列表「長(zhǎng)度」時(shí),同樣會(huì)報(bào)錯(cuò) IndexError: pop index out of range
1.3、不指定索引
「不指定索引」時(shí),默認(rèn)是 -1,也就是刪除最后一個(gè)元素
list1 = [1, 2, 3, 4] print('刪除前:', list1) list1.pop() print('刪除后:', list1)
輸出:
刪除前: [1, 2, 3, 4]
刪除后: [1, 2, 3]
2、返回被刪除的元素
pop() 可以理解為「彈出」元素,它會(huì)返回被刪除的元素,我們可以打印被刪除的元素,來判斷有沒有刪錯(cuò)。
list1 = [1, 2, 3, 4] print(list1.pop())
輸出:
4
3、不同類型的元素
上面的案例中,我們刪除的都是一個(gè)元素,這個(gè)很好理解。
對(duì)于列表中「嵌套」列表這類情況,會(huì)把列表整體當(dāng)做一個(gè)元素刪掉,比如下面這樣:
list1 = [1, 2, [1, 2, 3], 4] print('刪除前:', list1) list1.pop(2) print('刪除前:', list1)
輸出:
刪除前: [1, 2, [1, 2, 3], 4]
刪除前: [1, 2, 4]
列表中嵌套元祖、字典時(shí),也同樣整個(gè)刪除
list1 = [1, 2, {1, 2, 3}, 4] print('刪除前:', list1) list1.pop(2) print('刪除前:', list1)
輸出:
刪除前: [1, 2, {1, 2, 3}, 4]
刪除前: [1, 2, 4]
即使嵌套很多層,也會(huì)整個(gè)刪除
list1 = [1, 2, [1, [1, [1, 2]]], 4] print('刪除前:', list1) list1.pop(2) print('刪除前:', list1)
輸出:
刪除前: [1, 2, [1, [1, [1, 2]]], 4]
刪除前: [1, 2, 4]
4、常見錯(cuò)誤
列表的 pop() 一次只能刪除一個(gè)元素,否則會(huì)報(bào)錯(cuò) TypeError: pop expected at most 1 argument
pop() 的參數(shù)必須是int,只能根據(jù)索引刪除元素,否則會(huì)報(bào)錯(cuò) TypeError: ‘str’ object cannot be interpreted as an integer
到此這篇關(guān)于Python列表pop()函數(shù)使用實(shí)例詳解的文章就介紹到這了,更多相關(guān)Python列表pop()函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 微信之獲取好友昵稱并制作wordcloud的實(shí)例
今天小編就為大家分享一篇Python 微信之獲取好友昵稱并制作wordcloud的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-02-02Python實(shí)現(xiàn)時(shí)鐘顯示效果思路詳解
這篇文章主要介紹了Python實(shí)現(xiàn)時(shí)鐘顯示,需要的朋友可以參考下2018-04-04Python按條件篩選、剔除表格數(shù)據(jù)并繪制剔除前后的直方圖(示例代碼)
本文介紹基于Python語言,讀取Excel表格文件數(shù)據(jù),以其中某一列數(shù)據(jù)的值為標(biāo)準(zhǔn),對(duì)于這一列數(shù)據(jù)處于指定范圍的所有行,再用其他幾列數(shù)據(jù)的數(shù)值,加以數(shù)據(jù)篩選與剔除,感興趣的朋友跟隨小編一起看看吧2024-07-07Pytorch轉(zhuǎn)onnx、torchscript方式
這篇文章主要介紹了Pytorch轉(zhuǎn)onnx、torchscript方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05