I have 3 lists in Python.
list_a = [10., 20., 30., 12.]
list_b = [30., 20., 60., 12.]
list_c = [10., 80., 90., 12.]
I want to drop those elements in list_b
and list_c
where values in list_a
are <= 15
. Therefore results become:
list_b = [20., 60.]
list_c = [80., 90.]
Is there a way to do this without for loops? (list comprehensions are ok)
If you are using numpy as you said you are, in comments, you can simply create a boolean index from a
and mask elements in b
and c
:
import numpy as np
list_a = np.array([10., 20., 30., 12.])
list_b = np.array([30., 20., 60., 12.])
list_c = np.array([10., 80., 90., 12.])
list_b = list_b[list_a>15]
list_c = list_c[list_a>15]
print list_a
print list_b
print list_c
Output:
[ 10. 20. 30. 12.]
[ 20. 60.]
[ 80. 90.]
You can convert the lists_b
and list_c
to Python list type
by .tolist()
method.
You can use the little known itertools.compress
class to do this. See Filter list using Boolean index arrays
>>> import itertools
>>> list_a = [10., 20., 30., 12.]
>>> list_b = [30., 20., 60., 12.]
>>> list_c = [10., 80., 90., 12.]
>>> bool_list = [item > 15 for item in list_a]
>>> bool_list
[False, True, True, False]
>>> list_b = list(itertools.compress(list_b, bool_list))
>>> list_b
[20.0, 60.0]
>>> list_c = list(itertools.compress(list_c, bool_list))
>>> list_c
[80.0, 90.0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With