python中的数组过滤器?

kn3*_*n3l 62 python list filter

例如,我有两个列表

 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 
Run Code Online (Sandbox Code Playgroud)

在python中是否有内置函数来执行此操作?

Chi*_*chi 92

如果订单不重要,您应该使用set.difference.但是,如果您想保留订单,只需要一个简单的列表理解.

result = [a for a in A if a not in subset_of_A]
Run Code Online (Sandbox Code Playgroud)

编辑:正如德尔南所说,如果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]
Run Code Online (Sandbox Code Playgroud)

  • 这可以通过使`subset_of_A`成为一个真正的`set`来大大改进,它给出了'O(1)`成员资格测试(而不是像列表那样的'O(n)`). (14认同)

car*_*ett 44

是的,filter功能:

filter(lambda x: x not in subset_of_A, A)
Run Code Online (Sandbox Code Playgroud)

  • @modulitos`list(filter(...))` (7认同)
  • 请注意,在Python 2中,`filter`返回列表本身,而在Python 3中,它返回一个迭代器. (6认同)

eat*_*eat 7

不,在python中没有构建功能来实现这一点,因为简单地说:

set(A)- set(subset_of_A)
Run Code Online (Sandbox Code Playgroud)

将为您提供答案.


Ale*_*ler 6

set(A)-set(subset_of_A)给出您想要的结果集,但它不会保留原始订单.以下是订单保留:

[a for a in A if not a in subset_of_A]
Run Code Online (Sandbox Code Playgroud)


NPE*_*NPE 5

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