Python: Select subset from list based on index set
You could just use list comprehension:
property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]
or
property_asel = [property_a[i] for i in 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.
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))
I see 2 options.
-
Using numpy:
property_a = numpy.array([545., 656., 5.4, 33.]) property_b = numpy.array([ 1.2, 1.3, 2.3, 0.3]) good_objects = [True, False, False, True] good_indices = [0, 3] property_asel = property_a[good_objects] property_bsel = property_b[good_indices]
-
Using a list comprehension and zip it:
property_a = [545., 656., 5.4, 33.] property_b = [ 1.2, 1.3, 2.3, 0.3] good_objects = [True, False, False, True] good_indices = [0, 3] property_asel = [x for x, y in zip(property_a, good_objects) if y] property_bsel = [property_b[i] for i in good_indices]