程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

谈谈Python中pop与remove的用法

发布于2020-01-01 13:37     阅读(765)     评论(0)     点赞(18)     收藏(5)


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相同
复制代码

 

 



所属网站分类: 技术文章 > 博客

作者:齐天大圣

链接:https://www.pythonheidong.com/blog/article/198708/1940280749d5e5de2bec/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

18 0
收藏该文
已收藏

评论内容:(最多支持255个字符)