Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise "multiplication" of two lists with different type

Tags:

python

list

How to perform element wise "multiplication" between a list of strings and a list of boolean values?

For example if i have the following lists :

list_1=['A','B','C','D']

list_2=[True,False,True,False]

Expected output is :

list_output==['A','','C','']

Wherever there is True the string are maintained, and wherever there is False the string are replaced by empty string ('')

like image 205
Solomon123 Avatar asked Nov 17 '25 11:11

Solomon123


1 Answers

You can actually directly multiply corresponding elements after zipping the two lists since True is equivalent to 1 and False to 0. Multiplying a string by an integer repeats it that number of times.

res = [x * y for x, y in zip(list_1, list_2)]
like image 84
Unmitigated Avatar answered Nov 20 '25 02:11

Unmitigated



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!