在Python中的数组过滤器? [英] array filter in python?
本文介绍了在Python中的数组过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
A = [6,7,8,9,10,11,12 ]
subset_of_A = [6,9,12]; #A
的子集,结果应该是[7,8,10,11];其余的元素
Python中是否有内置函数? b $ b
解决方案
如果顺序不重要,应该使用 set.difference
。然而,如果你想保留订单,只需要简单的列表理解。
result = [a for a in A如果一个不是在subset_of_A]
编辑:如果 subset_of_A
是一个实际的 set
,因为检查集合
为O(1),而O(n)为列表。
A = [6 ,7,8,9,10,11,12]
subset_of_A = set([6,9,12])#A
的子集结果= [a for a in A如果一个不在[subset_of_A]
For example, I have two lists
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
Is there a built-in function in python to do this?
解决方案
If the order is not important, you should use set.difference
. However, if you want to retain order, a simple list comprehension is all it takes.
result = [a for a in A if a not in subset_of_A]
EDIT: As delnan says, performance will be substantially improved if subset_of_A
is an actual set
, since checking for membership in a set
is O(1) as compared to O(n) for a list.
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]
这篇关于在Python中的数组过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文