我想执行以下操作:
a=max(a,3)
b=min(b,3)
但有时a
和b
可能是None
我很高兴地发现,在max
的情况下,它可以很好地处理我所需的结果3
,但如果b
为None
,b
仍然存在None
...
任何人都可以想到一个优雅的小技巧,让min
返回数字,以防其中一个参数为无?
答案 0 :(得分:30)
为什么不创建没有None值的生成器?它更简单,更清洁。
>>> l=[None ,3]
>>> min(i for i in l if i is not None)
3
答案 1 :(得分:4)
Python 3的解决方案
<强>代码强>:
#variable lst是你的序列
min(filter(lambda x: x is not None, lst)) if any(lst) else None
<强>示例:强>
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
备注:强>
按顺序工作表现为数字和无。如果所有值都为None min()则引发异常
ValueError:min()arg是一个空序列
此代码解决此问题
<强>优点:强>
<强>缺点强>
答案 2 :(得分:3)
def max_none(a, b):
if a is None:
a = float('-inf')
if b is None:
b = float('-inf')
return max(a, b)
def min_none(a, b):
if a is None:
a = float('inf')
if b is None:
b = float('inf')
return min(a, b)
max_none(None, 3)
max_none(3, None)
min_none(None, 3)
min_none(3, None)
答案 3 :(得分:3)
这是一个内联装饰器,可用于过滤掉可能传递给函数的None值:
noNones = lambda fn : lambda *args : fn(a for a in args if a is not None)
print noNones(min)(None, 3)
print noNones(max)(None, 3)
打印:
3
3
答案 4 :(得分:2)
您可以使用内联if
和无穷大作为默认值,因为它适用于任何值:
a = max(a if a is not None else float('-inf'), 3)
b = min(b if b is not None else float('inf'), 3)
答案 5 :(得分:1)
我对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)
答案 6 :(得分:0)
a=max(a,3) if a is not None else 3
b=min(b,3) if b is not None else 3
答案 7 :(得分:0)
@ utdemir的答案对于提供的示例非常有用,但在某些情况下会引发错误。
如果您的列表中只有None
值,则会出现一个问题。如果您向min()
提供空序列,则会引发错误:
>>> mylist = [None, None]
>>> min(value for value in mylist if value)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
因此,此代码段可以防止错误:
def find_minimum(minimums):
potential_mins = (value for value in minimums if value is not None)
if potential_mins:
return min(potential_mins)
答案 8 :(得分:0)
我认为最干净的方法是使用过滤器内置函数
a = max(filter(None, [a, 3]))
b = min(filter(None, [b, 3]))