用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:17:48  来源:igfitidea点击:

List minimum in Python with None?

pythonlistmaxpython-2.xminimum

提问by c00kiemonster

Is there any clever in-built function or something that will return 1for 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 Nonevalues really bad!)

是否有任何巧妙的内置函数或会1min()下面的示例返回的东西?(我敢打赌它不返回任何东西是有充分理由的,但在我的特殊情况下,我需要它忽略None非常糟糕的值!)

>>> max([None, 1,2])
2
>>> min([None, 1,2])
>>> 

回答by nosklo

Noneis being returned

None正在被退回

>>> print min([None, 1,2])
None
>>> None < 1
True

If you want to return 1you have to filter the Noneaway:

如果你想返回,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。