[英]Given a list and a bitmask, how do I return the values at the indices that are True?
I start with the following list s
and bitmask b
: 我先从下面的列表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
How do I write some function apply_bitmask(s, b)
so that it returns 如何编写一些函数apply_bitmask(s, b)
以便它返回
['baa', 'have', 'you', 'any']
Python 3.1 itertools.compress (or Python 2.7's if you haven't upgraded yet) does exactly that (the list comprehension is a real close second): Python 3.1 itertools.compress (如果你还没有升级,则是Python 2.7 )就是这样(列表理解是一个非常接近的第二个):
import itertools
filtered = itertools.compress(s, b)
Note that this produces an iterator, not a list. 请注意,这会生成迭代器,而不是列表。 Saves memory, but if you need to iterate it several times or use indices, you can always use list(itertools.compress(s, b))
. 保存内存,但如果需要多次迭代或使用索引,则可以始终使用list(itertools.compress(s, b))
。 Still shorter. 还是更短。
[ item for item, flag in zip( s, b ) if flag == 1 ]
You can use list comprehensions : 您可以使用列表推导 :
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.
This first takes the original two lists, and zips them together, so that you get a (temporary - this is still inside the list comp!) list of pairs of words and their masks - something like [('baa',1), ('baa',0),...]
. 这首先取出原来的两个列表,并将它们拉到一起,这样你就得到了一个(临时的 - 这仍然在列表中!)一对单词和它们的掩码列表 - 类似于[('baa',1), ('baa',0),...]
。 Then only the words that have a mask of 1 ( if mask == 1
) are added to the newList
. 然后只将掩码为1的单词( if mask == 1
)添加到newList
。
另一种列表理解,无需使用zip
newList = [item for i, item in enumerate(s) if b[i]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.