谈谈Python中pop与remove的用法

2022-10-17,,,,

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相同

 

 

《谈谈Python中pop与remove的用法.doc》

下载本文的Word格式文档,以方便收藏与打印。