Python:根据索引集从列表中选择子集
我有几个具有相同数量条目的列表(每个条目都指定一个对象属性):
I have several lists having all the same number of entries (each specifying an object property):
property_a = [545., 656., 5.4, 33.]
property_b = [ 1.2, 1.3, 2.3, 0.3]
...
并列出具有相同长度的标志
and list with flags of the same length
good_objects = [True, False, False, True]
(可以很容易地用等效的索引列表代替:
(which could easily be substituted with an equivalent index list:
good_indices = [0, 3]
生成新列表property_asel
,property_bsel
,...仅包含True
条目或索引所指示的值的最简单方法是什么?
What is the easiest way to generate new lists property_asel
, property_bsel
, ... which contain only the values indicated either by the True
entries or the indices?
property_asel = [545., 33.]
property_bsel = [ 1.2, 0.3]
您可以只使用或
property_asel = [property_a[i] for i in good_indices]
后一种更快,因为good_indices
比property_a
的长度少,假设good_indices
是预先计算的,而不是即时生成的.
The latter one is faster because there are fewer good_indices
than the length of property_a
, assuming good_indices
are precomputed instead of generated on-the-fly.
编辑:第一个选项等效于从Python 2.7/3.1开始可用的itertools.compress
.参见 @Gary Kerr 的答案.
Edit: The first option is equivalent to itertools.compress
available since Python 2.7/3.1. See @Gary Kerr's answer.
property_asel = list(itertools.compress(property_a, good_objects))