给定一个列表和一个位掩码,如何返回索引为True的值? [英] Given a list and a bitmask, how do I return the values at the indices that are True?
本文介绍了给定一个列表和一个位掩码,如何返回索引为True的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从以下列表s
和位掩码b
开始:
I start with the following list s
and bitmask 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)
,以便它返回
How do I write some function apply_bitmask(s, b)
so that it returns
['baa', 'have', 'you', 'any']
推荐答案
Python 3.1 Python 2.7的如果您尚未升级),则完全可以做到这一点(列表理解是紧随其后的):
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):
import itertools
filtered = itertools.compress(s, b)
请注意,这将生成一个迭代器,而不是列表.节省内存,但是如果您需要对其进行多次迭代或使用索引,则可以始终使用list(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))
. Still shorter.
这篇关于给定一个列表和一个位掩码,如何返回索引为True的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文