Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

highest value that is less than 0 in a list that has mix of negative and positive values

Tags:

python

list

I have a list with the these values.

lst1 = [1,-2,-4,-8,-9,-12,0,39,12,-3,-7]

I need to get the max value that is less that zero.

If I do print max(last)- I get 39 and what is need is -2.

print max(p < 0 for p in lst1), I get True and not -2

like image 459
paddu Avatar asked Sep 05 '15 21:09

paddu


People also ask

How do you check if a list has only one element?

To check that the list contains only one element, you could use a couple of try , except statements to check that (1) you can access the first element, and (2) you can't access a second element. Really, the most Pythonic way is to just use len .

How do you check if two elements in a list are the same python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().

How to check if a number is greater than numbers in a list Python?

Use the all() function to check if all values in a list are greater than a certain number, e.g. if all(item > 2 for item in my_list): . The all() function will return True if all of the values in the list are greater than the specified number and False otherwise. Copied!


2 Answers

Never mind, I figured out and it should be

print max(p for p in lst1 if p < 0)
like image 174
paddu Avatar answered Sep 23 '22 19:09

paddu


just filter the list first:

max(filter(lambda x:x<0,ls))
like image 22
yurib Avatar answered Sep 22 '22 19:09

yurib