发布于2019-08-07 09:36 阅读(839) 评论(0) 点赞(5) 收藏(4)
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/9412/cbdcc0728eaa0cec6271/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!