[英]Deleting list elements based on condition
I have a list of lists: [word, good freq, bad freq, change_status]
我有一个列表:
[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.因此,如果
change_status > 0.3 and bad_freq < 5
那么我想删除与其对应的元素。
So the list_1 would be modified as,所以 list_1 将被修改为,
list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0]]
How do I selective do that?我如何有选择地做到这一点?
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.如果需要,您也可以使用
if not (item[2] < 5 and item[3] < 0.3)
作为条件。
Use the filter
function with an appropriate function.使用具有适当功能的
filter
功能。
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!请注意,即使您在问题中这么说, good也不满足您的条件(
20 < 5
为假)!
If you have many elements you might want to use the equivalent function from itertools:如果您有很多元素,您可能希望使用 itertools 中的等效函数:
from itertools import ifilter
filtered = ifilter(lambda x: x[3] <= 0.3 and x[2] < 5, list_1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.