简体   繁体   English

根据另一个布尔列表从一个列表中获取元素

[英]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. 我有两个大小相同的列表,一个是字符串列表,另一个是布尔值列表( TrueFalse ),并且仅当索引为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.

相关问题 根据另一个列表中的元素从一个列表中删除元素 - Remove element from one list based on elements in another list 根据另一个列表中的索引汇总一个列表中的元素 - Summing up elements from one list based on indices in another list 基于另一个列表中的元素重复一个列表中的元素 - Repeat elements in one list based on elements from another 如何从基于另一个列表的列表中过滤元素并获取百分比 - How to filter elements from a list based in another list and get percentages 根据另一个列表的元素更改一个列表中的元素 - Change elements in one list based on elements of another list 检查另一个列表中一个列表中的元素 - Check for elements in one list from another list 如何修改基于另一个列表的元素 - How to modify the elements of one list based on another 根据一个列表中的值是否在另一个列表中,形成 boolean 值的列表 - Form a list of boolean values based on if values from one list are in the other 为什么我不能从将一个列表附加到另一个列表中获取元素 - why I can not get the elements from appending one list into another 根据python中的另一个列表匹配列表的元素,其中一个列表的元素是另一个列表的子字符串 - match element of a list based on another list in python where elements of one list is the substring of elements of another list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM