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)
car*_*ett 44
是的,filter功能:
filter(lambda x: x not in subset_of_A, A)
Run Code Online (Sandbox Code Playgroud)
不,在python中没有构建功能来实现这一点,因为简单地说:
set(A)- set(subset_of_A)
Run Code Online (Sandbox Code Playgroud)
将为您提供答案.
set(A)-set(subset_of_A)给出您想要的结果集,但它不会保留原始订单.以下是订单保留:
[a for a in A if not a in subset_of_A]
Run Code Online (Sandbox Code Playgroud)