I have a list of values:
a = [1,2,3,4]
And a corresponding list of Booleans:
b = [True, True, False, True]
I want to map b onto a such that I get all values in a such that their corresponding value in b is 'True'. So the answer in this instance would be [1,2,4]
The only way I can think of doing is to loop through the elements of b, get the indices that are True, and then retrieve the corresponding index in a. So something like:
def maplist(l1, l2):
# list1 is a list of Booleans to map onto list2
l2_true = []
for el in range(len(l1)):
if l1[el] == True:
l2_true.append(l2[el])
return l2_true
Is there a better way to do this?
itertools.compress. For example:list(itertools.compress(a, b)). But I prefer list comprehension solutions.