使用布尔索引数组的过滤器列表 [英] Filter list using Boolean index arrays

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

问题描述

如何在不使用numpy的情况下使用布尔inddex数组过滤列表?

How can I use boolean inddex arrays to filter a list without using numpy?

例如:

>>> l = ['a','b','c']
>>> b = [True,False,False]
>>> l[b]

结果应为:

['a']

我知道numpy支持它,但想知道如何用Python解决.

I know numpy support it but want to know how to solve in Python.

>>> import numpy as np
>>> l = np.array(['a','b','c'])
>>> b = np.array([True,False,False])
>>> l[b]
array(['a'], 
      dtype='|S1')

推荐答案

Python不支持布尔索引,但

Python does not support boolean indexing but the itertools.compress function does exactly what you want. It return an iterator with means you need to use the list constructor to return a list.

>>> from itertools import compress
>>> l = ['a', 'b', 'c']
>>> b = [True, False, False]
>>> list(compress(l, b))
['a']

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

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