用 None 列出 Python 中的最小值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2295461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List minimum in Python with None?
提问by c00kiemonster
Is there any clever in-built function or something that will return 1
for the min()
example below? (I bet there is a solid reason for it not to return anything, but in my particular case I need it to disregard None
values really bad!)
是否有任何巧妙的内置函数或会1
为min()
下面的示例返回的东西?(我敢打赌它不返回任何东西是有充分理由的,但在我的特殊情况下,我需要它忽略None
非常糟糕的值!)
>>> max([None, 1,2])
2
>>> min([None, 1,2])
>>>
回答by nosklo
None
is being returned
None
正在被退回
>>> print min([None, 1,2])
None
>>> None < 1
True
If you want to return 1
you have to filter the None
away:
如果你想返回,1
你必须过滤None
掉:
>>> L = [None, 1, 2]
>>> min(x for x in L if x is not None)
1
回答by Adrien Plisson
using a generator expression:
使用生成器表达式:
>>> min(value for value in [None,1,2] if value is not None)
1
eventually, you may use filter:
最终,您可以使用过滤器:
>>> min(filter(lambda x: x is not None, [None,1,2]))
1
回答by gregory
Make None infinite for min():
为 min() 设置 None 无限:
def noneIsInfinite(value):
if value is None:
return float("inf")
else:
return value
>>> print min([1,2,None], key=noneIsInfinite)
1
Note: this approach works for python 3 as well.
注意:这种方法也适用于 python 3。