Python:根据索引集从列表中选择子集 [英] Python: Select subset from list based on index set

查看:522
本文介绍了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_aselproperty_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_indicesproperty_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))

这篇关于Python:根据索引集从列表中选择子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆