Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection elements of a list based on another 'True'/'False' list

Tags:

python

list

I have two lists of the same length. The first one contains strings. The second one - strings that can be either 'True' or 'False'.

If the nth element of the second list is 'True', I want to append the nth element of the first list to another list.

So if I have:

List1:

('sth1','sth2','sth3','sth4') 

List2:

('True','False','True','False')

The outcome should be List3:

('sth1','sth3').

How can I intersect two list in that way?

like image 282
reznik Avatar asked Jan 20 '17 11:01

reznik


1 Answers

Use zip:

result = [x for x, y in zip(xs, ys) if y == 'True']

Example:

xs = ('sth1','sth2','sth3','sth4')
ys = ('True','False','True','False')
result = [x for x, y in zip(xs, ys) if y == 'True']
result
['sth1', 'sth3']
like image 106
Reut Sharabani Avatar answered Nov 12 '22 03:11

Reut Sharabani