[英]Find minimum values in a python 3.3 list
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.如果
a
不包含任何负值或任何正值,则可能需要特殊处理。
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使用 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.注意:如果列表中没有 >= 0 的数字,这将返回 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.