Python中的数组过滤器?


84

例如,我有两个列表

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A


the result should be [7, 8, 10, 11]; the remaining elements 

python中是否有内置函数可以做到这一点?

Answers:


118

如果顺序不重要,则应使用set.difference。但是,如果要保留顺序,只需要简单的列表理解即可。

result = [a for a in A if a not in subset_of_A]

编辑:正如delnan所说,如果subset_of_A是实际值,性能将大大提高set,因为检查a中的成员资格set是O(1)而不是列表中的O(n)。

A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = set([6, 9, 12]) # the subset of A

result = [a for a in A if a not in subset_of_A]

14
并且可以通过创建subset_of_A一个real进行极大的改进set,它可以进行O(1)成员资格测试(而不是O(n)列表)。


7

不,在python中没有内置函数可以执行此操作,原因很简单:

set(A)- set(subset_of_A)

将为您提供答案。


1
尽管这适用于他的例子,可能有问题,如果重复列表中的A.元素
阿洛克迈索尔

6

set(A)-set(subset_of_A)提供您想要的结果集,但不会保留原始顺序。以下是订单保留:

[a for a in A if not a in subset_of_A]

5

tuple(set([6, 7, 8, 9, 10, 11, 12]).difference([6, 9, 12]))



3

这是几天前才问到的(但我找不到):

>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = set([6, 9, 12])
>>> [i for i in A if i not in subset_of_A]
[7, 8, 10, 11]

set从一开始就根据上下文使用s可能更好。然后,您可以像其他答案一样使用设置操作

但是,将列表转换为集合并仅针对这些操作返回比列表理解要慢。


2

使用Set类型:

A_set = Set([6,7,8,9,10,11,12])
subset_of_A_set = Set([6,9,12])

result = A_set - subset_of_A_set

1
>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])

1
>>> A           = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A  = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>> 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.