For example:
a=[-5,-3,-1,1,3,5]
I want to find a negative and a positive minimum.
example: negative
print(min(a)) = -5
positive
print(min(a)) = 1
For getting minimum negative:
min(a)
For getting minimum positive:
min(filter(lambda x:x>0,a))
>>> a = [-5,-3,-1,1,3,5]
>>> min(el for el in a if el < 0)
-5
>>> min(el for el in a if el > 0)
1
Special handling may be required if a
doesn't contain any negative or any positive values.
x = [-5,-3,-1,1,3,5]
# First min is actual min, second is based on absolute
sort = lambda x: [min(x),min([abs(i) for i in x] )]
print(sort(x))
[-5, 1]
[Program finished]
Using functools.reduce
>>> from functools import reduce
>>> a = [-5,-3,-1,2,3,5]
>>> reduce(lambda x,y: x if 0 <= x <=y else y if y>=0 else 0, a)
2
>>> min(a)
-5
>>>
Note: This will return 0 if there are no numbers >= 0 in the list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.