Roman
Roman

Reputation: 3241

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')

Upvotes: 6

Views: 6491

Answers (3)

Subham
Subham

Reputation: 411

Using enumerate

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

res = [item for i, item in enumerate(l) if b[i]]

print(res)

gives

['a']

Upvotes: 1

Sede
Sede

Reputation: 61293

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']

Upvotes: 11

Amadan
Amadan

Reputation: 198526

[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.

Upvotes: 5

Related Questions