Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mask a list using boolean values from another list

Tags:

python

list

I have a list like this:

x = [True, False, True, False]

and a list like this:

y = [a, b, c, d]

I would like to mask x over y to get this output:

output = [a, c]

I know how to do this using while/for loops, but I'm ideally looking for an elegant one-line of code using list comprehension.

like image 266
NBC Avatar asked Nov 28 '18 20:11

NBC


People also ask

How do you filter a boolean list in Python?

compress() to Filter list by Boolean list. The most elegant and straightforward method to perform this particular task is to use the inbuilt functionality of compress() to filter out all the elements from a list that exists at Truth positions with respect to the index of another list.

How do you filter a list by another list in Python?

Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x , and False otherwise. How to Filter a List in Python?

What is boolean masking?

Boolean masking, also called boolean indexing, is a feature in Python NumPy that allows for the filtering of values in numpy arrays.


2 Answers

You can use zip and a list comprehension to perform a filter operation on y based on corresponding truth values in x:

x = [True, False, True, False]
y = ["a", "b", "c", "d"]

print([b for a, b in zip(x, y) if a])

Output:

['a', 'c']

itertools.compress also does this:

>>> from itertools import compress
>>> x = [True, False, True, False]
>>> y = ["a", "b", "c", "d"]
>>> list(compress(y, x))
['a', 'c']
like image 161
ggorlen Avatar answered Sep 23 '22 11:09

ggorlen


There are several ways to do this.

The simplest way would be to zip the two lists together and use a list comprehension to keep the items you want.

x = [True, False, True, False]
y = ['a', 'b', 'c', 'd']

print([item for keep, item in zip(x, y) if keep])

You can also convert the y array to a numpy array and use the x array to mask the numpy array.

import numpy as np

x = [True, False, True, False]
y = ['a', 'b', 'c', 'd']

print(list(np.array(y)[x]))

Finally, you can create an empty list, iterate through the x and y arrays using their indexes, and append elements in y to the empty list if the corresponding element in x is True.

x = [True, False, True, False]
y = ['a', 'b', 'c', 'd']

temp = []

for index in range(len(y)):
    if x[index]:
        temp.append(y[index])

print(temp)
like image 33
tdurnford Avatar answered Sep 23 '22 11:09

tdurnford