python中的数组过滤器? [英] array filter in python?

查看:28
本文介绍了python中的数组过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有两个列表

 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 中是否有内置函数来执行此操作?

Is there a built-in function in python to do this?

推荐答案

如果顺序不重要,你应该使用set.difference.但是,如果您想保持顺序,只需简单的列表推导即可.

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]

正如 delnan 所说,如果 subset_of_A 是一个实际的 set,性能将得到显着提高,因为检查 中的成员资格>set 与列表的 O(n) 相比是 O(1).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆