Python reduce list by mask -
Python reduce list by mask -
this question has reply here:
filtering list based on list of booleans 4 answersi want create smaller list based on mask: illustration list [1, 2, 3]
, mask: [1, 0, 1]
should give me [1, 3]
.
i have written next function:
def reducing(arr, mask): out = [] in range(len(mask)): if mask[i]: out.append(arr[i]) homecoming out
which works, think can done simpler cut down function (all in - reducing list :-) ) or comprehension. can help this?
you can utilize itertools.compress
, this
>>> itertools import compress >>> list(compress([1, 2, 3], [1, 0, 1])) [1, 3]
otherwise, can filter them list comprehension, this
>>> [item item, mask in zip([1, 2, 3], [1, 0, 1]) if mask] [1, 3]
even simpler, instead of using zip
, can skip items based on index, this
>>> data, mask = [1, 2, 3], [1, 0, 1] >>> [item index, item in enumerate(data) if mask[index]] [1, 3]
or can utilize simple looping index, this
>>> [data[index] index in range(len(data)) if mask[index]] [1, 3]
python list
Comments
Post a Comment