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