Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from python list based on filter

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)

like image 919
user308827 Avatar asked Nov 28 '22 22:11

user308827


2 Answers

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.

like image 193
Mohammad Yusuf Avatar answered Dec 04 '22 01:12

Mohammad Yusuf


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]
like image 25
styvane Avatar answered Dec 04 '22 00:12

styvane