Home > OS >  pythonic way to vectorize ifelse over list
pythonic way to vectorize ifelse over list

Time:10-24

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?

CodePudding user response:

using zip?

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

CodePudding user response:

Alternatively, using tuple indices with zip:

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

CodePudding user response:

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]

  • Related