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.
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.
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?
Boolean masking, also called boolean indexing, is a feature in Python NumPy that allows for the filtering of values in numpy arrays.
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']
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)
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