Jon*_*han 30 python python-2.x
我想执行以下操作:
a=max(a,3)
b=min(b,3)
Run Code Online (Sandbox Code Playgroud)
但有时a也b可能None.
我很高兴地发现,如果max它很好地工作,给出我所需的结果3,但如果b是None,b仍然None...
任何人都可以想到一个优雅的小技巧min,如果其中一个参数在None中,则返回数字?
utd*_*mir 34
为什么不创建没有None值的生成器?它更简洁,更清洁.
>>> l=[None ,3]
>>> min(i for i in l if i is not None)
3
Run Code Online (Sandbox Code Playgroud)
我的 Python 3(3.4 及更高版本)解决方案:
min((x for x in lst if x is not None), default=None)
max((x for x in lst if x is not None), default=None)
Run Code Online (Sandbox Code Playgroud)
Python 3的解决方案
代码:
#变量lst是你的序列
min(filter(lambda x: x is not None, lst)) if any(lst) else None
Run Code Online (Sandbox Code Playgroud)
例子:
In [3]: lst = [None, 1, None]
In [4]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[4]: 1
In [5]: lst = [-4, None, 11]
In [6]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[6]: -4
In [7]: lst = [0, 7, -79]
In [8]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[8]: -79
In [9]: lst = [None, None, None]
In [10]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
In [11]: print(min(filter(lambda x: x is not None, lst)) if any(lst) else None)
None
Run Code Online (Sandbox Code Playgroud)
笔记:
按顺序显示为数字和无。如果所有值均为None,则min()引发异常
ValueError:min()arg为空序列
这段代码完全解决了这个问题
优点:
缺点