根据布尔值列表过滤列表 [英] Filtering a list based on a list of booleans

查看:245
本文介绍了根据布尔值列表过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个值列表,在给定布尔值列表中的值的情况下,我需要过滤这些值:

I have a list of values which I need to filter given the values in a list of booleans:

list_a = [1, 2, 4, 6]
filter = [True, False, True, False]

我用以下行生成一个新的过滤列表:

I generate a new filtered list with the following line:

filtered_list = [i for indx,i in enumerate(list_a) if filter[indx] == True]

其结果是:

print filtered_list
[1,4]

这条线有效,但是(对我而言)看起来有点过大,我想知道是否有更简单的方法来实现这一目标.

The line works but looks (to me) a bit overkill and I was wondering if there was a simpler way to achieve the same.

下面的答案中给出了两个好的建议的总结:

Summary of two good advices given in the answers below:

1-不要像我那样命名列表filter,因为它是内置函数.

1- Don't name a list filter like I did because it is a built-in function.

2-不要像我对if filter[idx]==True..所做的那样将其与True进行比较,因为这是不必要的.只需使用if filter[idx]就足够了.

2- Don't compare things to True like I did with if filter[idx]==True.. since it's unnecessary. Just using if filter[idx] is enough.

推荐答案

您正在寻找 itertools.compress :

You're looking for itertools.compress:

>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]

时间比较(py3.x):

>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]  #winner
100000 loops, best of 3: 1.98 us per loop

>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil))              #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop

>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil))              #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] 
100 loops, best of 3: 7.65 ms per loop

不要使用filter作为变量名,它是一个内置函数.

Don't use filter as a variable name, it is a built-in function.

这篇关于根据布尔值列表过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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