[英]Get elements from one list based on another boolean list
I have two lists of the same size, one is a list of strings, and the other a list of booleans ( True
, False
) and I want to return a list of strings only if the index is True. 我有两个大小相同的列表,一个是字符串列表,另一个是布尔值列表( True
, False
),并且仅当索引为True时,我才想返回字符串列表。
b_list = [True, False, True]
s_list = ['abc', 'sfsfsfsf', 'def']
want 想
s_list = ['abc','def']
Use itertools.compress
使用itertools.compress
compress(data, selectors) : Return data elements corresponding to true selectors elements compress(data,selectors) :返回与真正的选择器元素相对应的数据元素
So s_list
is data and b_list
is selectors : 所以s_list
是数据 , b_list
是选择器 :
In [8]: import itertools
In [9]: list(itertools.compress(s_list, b_list))
Out[9]: ['abc', 'def']
如果没有使用列表理解的itertools
:
[y for (x,y) in zip(b_list, s_list) if x]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.