删除Python列表元素 [英] Remove Python list element
本文介绍了删除Python列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表
l1 = [1,2,3,4,5,6]
l2 = [3,2]
我要删除的是l2中的列表l1的元素,因为我已经做了类似的事情,
what i want is to remove the element of list l1 which is in l2, for that i have done something like this,
for x in l1:
if x in l2:
l1.remove(x)
它提供类似
[1, 3, 4, 5, 6]
但输出应类似于
[1, 4, 5, 6]
任何人都可以阐明这一点.
can any one shed light on this.
推荐答案
这很容易解释.
考虑您拥有的第一个数组:
consider the first array you have:
| 1 | 2 | 3 | 4 | 5 | 6 |
现在开始迭代
| 1 | 2 | 3 | 4 | 5 | 6 |
^
什么也没有发生,迭代器会递增
Nothing happens, iterator increments
| 1 | 2 | 3 | 4 | 5 | 6 |
^
2被删除
| 1 | 3 | 4 | 5 | 6 |
^
迭代器增量
| 1 | 3 | 4 | 5 | 6 |
^
瞧,还有3个.
解决方案是迭代向量的副本,例如
The solution is to iterate ove a copy of the vector e.g.
for x in l1[:]: <- slice on entire array
if x in l2:
l1.remove(x)
或反向迭代:
for x in reversed(l1):
if x in l2:
l1.remove(x)
这样的行为:
| 1 | 2 | 3 | 4 | 5 | 6 |
^
| 1 | 2 | 3 | 4 | 5 | 6 |
^
| 1 | 2 | 4 | 5 | 6 |
^
| 1 | 2 | 4 | 5 | 6 |
^
| 1 | 4 | 5 | 6 |
^
| 1 | 4 | 5 | 6 |
^
这篇关于删除Python列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文