Skip to main content
 首页 » 编程设计

python之如何使用来自另一个列表的 bool 值来屏蔽列表

2025年05月04日12lexus

我有一个这样的列表:

x = [True, False, True, False] 

和这样的列表:

y = [a, b, c, d] 

我想在 y 上屏蔽 x 以获得此输出:

output = [a, c] 

我知道如何使用 while/for 循环来做到这一点,但理想情况下我正在寻找使用列表理解的优雅的单行代码。

请您参考如下方法:

您可以使用zip 和列表理解来根据x 中相应的真值对y 执行过滤操作:

x = [True, False, True, False] 
y = ["a", "b", "c", "d"] 
 
print([b for a, b in zip(x, y) if a]) 

输出:

['a', 'c'] 

itertools.compress也这样做:

>>> from itertools import compress 
>>> x = [True, False, True, False] 
>>> y = ["a", "b", "c", "d"] 
>>> list(compress(y, x)) 
['a', 'c']