談談Python中pop與remove的用法


remove() 函數用於移除列表中某個值的第一個匹配項。

remove()方法語法:  list.remove(obj)

如果obj不在列表中會引發 ValueError 錯誤,通常先使用count方法查看有多少個obj

pop() 函數用於移除列表中的一個元素(默認最后一個元素),並且返回該元素的值。

pop()方法語法:  list.pop(obj=list[-1])

接下來發現網上的另一篇文章貌似說的不是很合理

https://www.jb51.net/article/132501.htm

a_list = ['a', 'b', 'c', 'd', 'e']
b_list = ['b', 'c']
for i in a_list:
    if i in b_list:
        a_list.remove(i)
print(a_list)
# 輸出 ['a', 'c', 'd', 'e']

a_list = ['a', 'b', 'c', 'd', 'e']
b_list = ['b', 'c']
for i in a_list:
    if i in b_list:
        idl = a_list.index(i)
        a_list.pop(idl)
print(a_list)
# 輸出 ['a', 'c', 'd', 'e']

為什么元素‘c’未被刪除呢?那篇文章說x已經不是原來的x,好吧先看看以下的代碼吧

x = ['a', 'b', 'c', 'd']
print(id(x))
x.remove('b')
print(x)
print(id(x))
# 2071261855944
# ['a', 'c', 'd']
# 2071261855944

y = ['a', 'b', 'c', 'd']
print(id(y))
y.pop(2)
print(y)
print(id(y))
# 2071261858056
# [1, 2, 4]
# 2071261858056

這很明顯經過remove與pop刪除元素之后,地址並沒有改變,所以應該不是重新賦值。

針對使用for循環刪除元素來談一談個人看法,為了方便表達,直接解釋代碼,如下

a_list = ['a', 'b', 'c', 'c', 'd', 'e']
# 在元素‘c’后面又增加一個‘c’

b_list = ['b', 'c']
for i in a_list:
    if i in b_list:
        a_list.remove(i)
print(a_list)
# 依然輸出 ['a', 'c', 'd', 'e'] ,這說明
# 當remove刪除‘b’元素時第一個‘c’移動到‘b’的位置
# 第二遍循環遍歷時for循環是從上一次循環的下個索引位置開始的
# 此時就刪除了第二個‘c’,第一個“逃過一劫”

a_list = ['a', 'b', 'c', 'c', 'd', 'e']
# 在元素‘c’后面又增加一個‘c’

b_list = ['b', 'c']
for i in a_list:
    if i in b_list:
        idl = a_list.index(i)
        a_list.pop(idl)
print(a_list)
# 同樣輸出 ['a', 'c', 'd', 'e']
# 原理同remove相同

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM