Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pythonic way to vectorize ifelse over list

Tags:

python

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?

like image 419
gaut Avatar asked Aug 03 '26 13:08

gaut


1 Answers

using zip?

>>> [-a if b in ('yes','yep') else a for a,b in zip(lista, listb)]
[-1, 2, -4]
like image 155
koyeung Avatar answered Aug 06 '26 02:08

koyeung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!