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]
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]
You could just use list comprehension:
or
The latter one is faster because there are fewer
good_indicesthan the length ofproperty_a, assuminggood_indicesare precomputed instead of generated on-the-fly.Edit: The first option is equivalent to
itertools.compressavailable since Python 2.7/3.1. See @Gary Kerr‘s answer.