10

我从以下列表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']
4

4 回答 4

19

Python 3.1 itertools.compress(或者Python 2.7,如果你还没有升级的话)正是这样做的(列表理解紧随其后):

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

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

于 2010-08-24T10:31:23.600 回答
11
[ item for item, flag in zip( s, b ) if flag == 1 ]
于 2010-08-24T10:12:41.727 回答
8

您可以使用列表推导

newList = [word for (word, mask) in zip(s,b) if mask]
# Note: Could also use 'if mask == blah', if mask is not a boolean-compatible type.

这首先获取原始的两个列表,并将它们压缩在一起,这样你就得到了一个(临时的 - 这仍然在列表 comp 中!)成对的单词及其掩码列表 - 类似于[('baa',1), ('baa',0),...]. 然后仅将掩码为 1 ( if mask == 1) 的单词添加到newList.

于 2010-08-24T10:14:35.077 回答
0

列表理解的另一种方法,不使用 zip

newList = [item for i, item in enumerate(s) if b[i]]
于 2016-12-07T21:27:33.037 回答