pythonic way to vectorize ifelse over list

Question:

What is the most pythonic way to reverse the elements of one list based on another equally-sized list?

lista = [1,2,4]
listb = ['yes', 'no', 'yep']

# expecting [-1, 2,-4]

[[-x if y in ['yes','yep'] else x for x in lista] for y in listb]
# yields [[-1, -2, -4], [1, 2, 4], [-1, -2, -4]]

if listb[i] is yes or yep, result[i] should be the opposite of lista.

Maybe a lambda function applied in list comprehension?

Asked By: gaut

||

Answers:

using zip?

>>> [-a if b in ('yes','yep') else a for a,b in zip(lista, listb)]
[-1, 2, -4]
Answered By: koyeung

Alternatively, using tuple indices with zip:

[(x,-x)[y in ('yes','yep')] for x,y in zip(lista,listb)] 
# [-1, 2, -4]
Answered By: Arifa Chan

Another interesting solution is using itertools.starmap and zip:

import itertools as it    
l = list(it.starmap(lambda x, y: -x if y in ('yes', 'yep') else x, zip(lista, listb)))
print(l)

Output: [-1, 2, -4]

Answered By: Carmoreno
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.