Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove negative values from a list using lambda functions by python

I have implemented a lambda function to sort a list. now i want to remove all the negative objects from the list by using lambda functions .

dto_list.sort(key=lambda x: x.count, reverse=True)

any one know a way to write the lambda expression to do it? I could not find a proper tutorial

like image 444
Evlikosh Dawark Avatar asked Jan 16 '23 16:01

Evlikosh Dawark


1 Answers

Not very pythonic but here is how to do it with a lambda

>>> L = list(range(-10,10))
>>> L
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x >= 0, L)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

Most people would use a list comprehension

>>> [x for x in L if x >= 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
like image 100
Nick Craig-Wood Avatar answered Jan 30 '23 19:01

Nick Craig-Wood