码迷,mamicode.com
首页 > 编程语言 > 详细

谈谈Python中pop与remove的用法

时间:2019-08-06 22:41:16      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:remove   输出   返回   赋值   ror   pre   span   原来   style   

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的用法

标签:remove   输出   返回   赋值   ror   pre   span   原来   style   

原文地址:https://www.cnblogs.com/yang901112/p/11312292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!