Python reduce list by mask -



Python reduce list by mask -

this question has reply here:

filtering list based on list of booleans 4 answers

i 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

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -