简体   繁体   English

给定一个列表和一个位掩码,如何返回True为真的索引值?

[英]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.

相关问题 我如何获得函数startwith()为true的值的索引? - How do I get indices of values where function startswith() is true? 如何返回给定索引处的值被新值替换的数组? - How to return an array with values at given indices replaced by new values? 如何从给定的顶点索引列表生成边列表? - How do I a generate a list of edges from a given list of vertex indices? 如何用给定的值列表和索引列表填充 python 中的数组? - How to fill an array in python with given list of values and list of indices? 在给定索引处将给定值分配给列表的元素 - Assigning given values to elements of a list at given indices 如何返回列表中评估为 true 的元素? - How do I return the element in a list that evaluate to true? 在给定数据框值或索引列表的情况下,如何屏蔽数据框 - How to mask a dataframe given a list of values or indices in the dataframe 如何通过条件选择从Pandas DataFrame返回列的列表,其中行中的所有值均为True? - How do I return a list of columns from a Pandas DataFrame, via conditional selection, where all the values in a row are True? 获取 boolean 列表中真值的索引 - Getting indices of True values in a boolean list 如何使用列表索引返回数据列而不是行? - How do I use list indices to return columns of data instead of rows?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM