Home > Back-end >  Python List comprehension: Add Element to a list if condition in another list (with same length) is
Python List comprehension: Add Element to a list if condition in another list (with same length) is

Time:10-22

let's say I have an array

a =  [0.42 0.18 1.54 2.9  1.81 2.35 0.18 1.54 2.92]

which has the following (element-wise) logical state:

[False  True False False False False  True False False]

Is there a nice way to use a list comprehension to only add the True elements to a new list? Additional question: True elements from a shall be popped out afterwards (as they are now already processed)

CodePudding user response:

you can do it like this:

>>> a =  [0.42, 0.18, 1.54, 2.9,  1.81, 2.35, 0.18, 1.54, 2.92]
>>> b = [False, True, False, False, False, False,  True, False, False]
>>> c = [num for num, truth_value in zip(a, b) if truth_value]
>>> c
[0.18, 0.18]

if you find it difficult to understand just let me know from comment.

CodePudding user response:

Just to provide an alternative, this can also be done using itertools.compress (Python 3.1 or later). compress(a, b) makes an iterator which provides elements of a whose corresponding element in b evaluates to true.

For example:

>>> a =  [0.42, 0.18, 1.54, 2.9, 1.81, 2.35, 0.18, 1.54, 2.92]
>>> b = [False, True, False, False, False, False, True, False, False]
>>>
>>> c = list(itertools.compress(a, b))
>>> c
[0.18, 0.18]

It would still be necessary to remove those elements from a, either using a list comprehension, or the same technique, but flipping the boolean values, which is somewhat less elegant:

a = list(compress(a, (not x for x in b)))
  • Related