首页 > 解决方案 > 如何使用另一个列表中的布尔值屏蔽列表

问题描述

我有一个这样的列表:

x = [True, False, True, False]

和这样的列表:

y = [a, b, c, d]

我想掩盖xy获得此输出:

output = [a, c]

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

标签: pythonlist

解决方案


您可以使用和列表推导根据以下中的相应真值zip执行过滤操作:yx

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

推荐阅读