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

我只是一个虾纸丫 提交于 2021-02-18 07:31:48

问题


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?


回答1:


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']



回答2:


Or use numpy:

import numpy as np
filtered = np.array(List1)[np.array(List2)]

Btw this only works if the elements inside List2 are True/False, not if they are "True"/"False".




回答3:


If you didn't know about zip :

l1 = ('sth1','sth2','sth3','sth4')
l2 = ('True','False','True','False')
l = [x for i,x in enumerate(l1) if l2[i]=='True']
print l
#=> ['sth1', 'sth3']

It would be shorter with a tuple of booleans :

l1 = ('sth1','sth2','sth3','sth4')
l2 = (True,False,True,False)

l = [x for i,x in enumerate(l1) if l2[i]]
print l



回答4:


Simplest way is to use itertools.compress method as follows.

import itertools

list1 = ('sth1','sth2','sth3','sth4')
list2 = ('True','False','True','False')
list2 = map(lambda x: x == 'True', list2)

result = list(itertools.compress(list1, list2))

compress method returns an iterator, so you that is why you need to wrap the iterator object in list

I hope it helps.



来源:https://stackoverflow.com/questions/41762592/selection-elements-of-a-list-based-on-another-true-false-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!