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 res
Solution 1:
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']
Solution 2:
[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.
Solution 3:
Using enumerate
l = ['a','b','c']
b = [True,False,False]
res = [item for i, item inenumerate(l) if b[i]]
print(res)
gives
['a']
Post a Comment for "Filter List Using Boolean Index Arrays"