简体   繁体   中英

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 = ['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

['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):

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)) . 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),...] . Then only the words that have a mask of 1 ( if mask == 1 ) are added to the newList .

另一种列表理解,无需使用zip

newList = [item for i, item in enumerate(s) if b[i]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM