Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting list elements based on condition

I have a list of lists: [word, good freq, bad freq, change_status]

list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]] 

I would like to delete from the list all elements which don't satisfy a condition.

So if change_status > 0.3 and bad_freq < 5 then I would like to delete that the elements corresponding to it.

So the list_1 would be modified as,

list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0]] 

How do I selective do that?

like image 509
Zenvega Avatar asked Oct 01 '11 23:10

Zenvega


People also ask

How do you remove an element from a list based on condition?

To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.

How do you remove an element from a list based on value?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.


2 Answers

list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]] list_1 = [item for item in list_1 if item[2] >= 5 or item[3] >= 0.3] 

You can also use if not (item[2] < 5 and item[3] < 0.3) for the condition if you want.

like image 104
agf Avatar answered Oct 14 '22 13:10

agf


Use the filter function with an appropriate function.

list_1 = filter(lambda x: x[3] <= 0.3 and x[2] < 5, list_1) 

Demo:

In [1]: list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]] In [2]: filter(lambda x: x[3] <= 0.3 and x[2] < 5, list_1) Out[2]: [['bad', 10, 0, 0.0]] 

Note that good doesn't satisfy your condition (20 < 5 is false) even though you said so in your question!


If you have many elements you might want to use the equivalent function from itertools:

from itertools import ifilter filtered = ifilter(lambda x: x[3] <= 0.3 and x[2] < 5, list_1) 
like image 31
ThiefMaster Avatar answered Oct 14 '22 12:10

ThiefMaster