Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list using Boolean index arrays

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

For example:

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

The result should be:

['a']

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')
like image 481
Roman Avatar asked Jun 15 '15 05:06

Roman


People also ask

What is boolean filter?

filter(Boolean)` just removes values from a list which are "falsey", like empty strings or null.

Can you have a list of booleans?

A boolean list is a list that has no holes and contains only the boolean values true and false (see Chapter Booleans). In function names we call boolean lists blist for brevity.


2 Answers

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']
like image 123
styvane Avatar answered Oct 04 '22 00:10

styvane


[a for a, t in zip(l, b) if t]
# => ["a"]

A bit more efficient, use iterator version:

from itertools import izip
[a for a, t in izip(l, b) if t]
# => ["a"]

EDIT: user3100115's version is nicer.

like image 28
Amadan Avatar answered Oct 04 '22 00:10

Amadan