python - 给定一个列表和一个位掩码,我如何返回 True 索引处的值?

标签 python list sequence tuples bitmask

我从以下列表 s 和位掩码 b 开始:

s = ['baa', 'baa', 'black', 'sheep', 'have', 'you', 'any', 'wool']
b = [1, 0, 0, 0, 1, 1, 1, 0] # or any iterable with boolean values

我如何编写一些函数 apply_bitmask(s, b) 以便它返回

['baa', 'have', 'you', 'any']

最佳答案

Python 3.1 itertools.compress (或者 Python 2.7's 如果您还没有升级)就是这样做的(列表理解紧随其后):

import itertools
filtered = itertools.compress(s, b)

请注意,这会生成一个迭代器,而不是一个列表。节省内存,但如果您需要多次迭代它或使用索引,您始终可以使用 list(itertools.compress(s, b))。更短。

关于python - 给定一个列表和一个位掩码,我如何返回 True 索引处的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3555375/

相关文章:

python - 在 Python 中修复深度树

python - 如何在 Koding.com 上部署 Flask 应用程序

list - 获取列表中的第 N 个元素作为列表而不是 LISP 中的数字?

list - Prolog中列表的偶数和奇数之和

java - 创建序列时出现 SQL 错误

r - 在没有时区的 R 中创建日期和时间序列

python - 帮助在重新加载或子进程之间进行选择

python - PyQt4 "Mainwindow.show()"给出类型错误

java - 将整数列表排序为 Java 中的字符串列表

python - 在 SQLAlchemy 中使用序列生成字符串主键