python - 如何使用另一个列表中的布尔值屏蔽列表
问题描述
我有一个这样的列表:
x = [True, False, True, False]
和这样的列表:
y = [a, b, c, d]
我想掩盖x
以y
获得此输出:
output = [a, c]
我知道如何使用while
/for
循环来做到这一点,但理想情况下,我正在寻找使用列表理解的优雅的单行代码。
解决方案
您可以使用和列表推导根据以下中的相应真值zip
执行过滤操作:y
x
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']
推荐阅读
- django - Django 弹性搜索:AttributeError:类型对象“PostDocument”没有属性“Django”
- c# - 以不同的顺序对集合中的对象执行几种方法
- php - 阻止直接访问文件的问题
- python - Python Django Queryset 仅从日期获取月份和年份
- python - 如何读取一些文件数据并将其写入另一个文件?
- jquery - JQuery删除限制在外部容器中的重复项
- elixir - 开始登录后用户不存在
- python - 如何清除 IDLE shell 中所有文本的屏幕?
- azure - 如何使用 ADF 表达式生成器提取两个字符之间的字符串?
- assembly - 在用户输入中查找第一个和最后一个大写字母