Deleting list elements based on condition

我的梦境 提交于 2019-11-27 01:48:52
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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!