Python:min(无,x)

Jon*_*han 30 python python-2.x

我想执行以下操作:

a=max(a,3)
b=min(b,3)
Run Code Online (Sandbox Code Playgroud)

但有时ab可能None.
我很高兴地发现,如果max它很好地工作,给出我所需的结果3,但如果bNone,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)

  • 像这样的解决方案的一个潜在问题是它对于列出的示例工作正常,但如果你有一个带有`[None,None]`的列表,`min()`函数将失败,因为你没有给它一个有效的论点. (8认同)
  • 不需要列表理解.仍然+1(提前 - 严重,请删除括号),这是一个简洁的解决方案. (3认同)
  • 是.如果genexpr是函数调用的唯一参数,则生成器表达式周围的parens是可选的. (2认同)
  • @KevinLondon,根据您想要的行为将最小值的默认值指定为 0 或 None 。```min((x for x in [None,None] if x is not None), default=None)``` (2认同)

R1t*_*chY 6

我的 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)


PAD*_*MKO 5

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为空序列

这段代码完全解决了这个问题

优点:

  1. 如果无顺序显示则工作
  2. 使用Python 3
  3. max()也会工作

缺点

  1. 列表中需要多个非零变量。即[0,None]失败。
  2. 需要一个变量(例如lst)或需要重复序列