[英]Using list comprehension to keep items not in second list
I am trying to use list comprehension to remove a number of items from a list by just keeping those not specified. 我正在尝试使用列表推导通过仅保留未指定的项目从列表中删除许多项目。
For example if I have 2 lists a = [1,3,5,7,10]
and b = [2,4]
I want to keep all items from a
that are not at an index corresponding to a number in b
. 例如,如果我有2个列表,则
a = [1,3,5,7,10]
和b = [2,4]
我想保留a
中所有不在索引中与b
的数字相对应的项。
Now, I tried to use y = [a[x] for x not in b]
but this produces a SyntaxError. 现在,我尝试将
y = [a[x] for x not in b]
但这会产生SyntaxError。
y = [a[x] for x in b]
works fine and keeps just exact the elements that i want removed. y = [a[x] for x in b]
可以正常工作,并保持与我要删除的元素完全相同。
So how do I achieve this? 那么我该如何实现呢? And on a side note, is this a good way to do it or should I use
del
? 另外,这是一个好方法还是应该使用
del
?
You can use enumerate()
and look up indexes in b
: 您可以使用
enumerate()
并在b
查找索引:
>>> a = [1, 3, 5, 7, 10]
>>> b = [2, 4]
>>> [item for index, item in enumerate(a) if index not in b]
[1, 3, 7]
Note that to improve the lookup time, better have the b
as a set instead of a list. 请注意,为缩短查找时间,最好将
b
设置为列表而不是列表。 Lookups into sets are O(1)
on average while in a list - O(n)
where n
is the length of the list. 在列表中查找集合的平均次数为
O(1)
O(n)
,其中n
是列表的长度。
Guess you're looking for somthing like : 猜猜您在寻找类似的东西:
[ x for x in a if a.index(x) not in b ]
Or, using filter: 或者,使用过滤器:
filter(lambda x : a.index(x) not in b , a)
试试这个会起作用
[j for i,j in enumerate(a) if i not in b ]
after this: 在这之后:
y = [a[x] for x in b]
just add: 只需添加:
for x in y:
a.remove(x)
then you end up with a stripped down list in a 那么您最终会在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.