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')
filter(Boolean)` just removes values from a list which are "falsey", like empty strings or null.
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.
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']
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With