我想执行以下操作:的Python:分钟(无,X)
a=max(a,3)
b=min(b,3)
然而有时a
和b
可以是None
。
我很高兴地发现,在max
它的作品了很好,给我的要求的结果3
的情况,但是如果b
为None
,b
仍然None
...
任何人都可以想到的是优雅的小动作,使min
返回数字,以防其中一个参数在无?
我想执行以下操作:的Python:分钟(无,X)
a=max(a,3)
b=min(b,3)
然而有时a
和b
可以是None
。
我很高兴地发现,在max
它的作品了很好,给我的要求的结果3
的情况,但是如果b
为None
,b
仍然None
...
任何人都可以想到的是优雅的小动作,使min
返回数字,以防其中一个参数在无?
你为什么不只是创建一个没有无值的发电机?它更简单,更清洁。
>>> l=[None ,3]
>>> min(i for i in l if i is not None)
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)
请注意,这只适用于默认值为0的情况。传递0而不是'None'仍会触发传递默认值,但不会因为默认值为0(和'0 == 0.0 == 0j'),所以更改该值。 – delnan 2011-06-06 16:16:45
OP表示max不是问题。如果b是负值,会发生什么? – 2011-06-06 16:16:58
修改答案。 – 2011-06-07 08:52:24
下面是一个行内装饰,你可以用它来过滤掉可能被传递给函数无值:
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
a=max(a,3) if a is not None else 3
b=min(b,3) if b is not None else 3
@ 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)
一个为Python 3
一个解决方案代码:
#变量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
注:
曾在序列呈现为号码以及无。如果所有的值是无分()引发异常
ValueError: min() arg is an empty sequence
此代码解决此问题,在所有
优点:
缺点
需要一个变量(例如LST)或需要重复序列
它没有做正确的事。它恰好在两种情况中的一种情况下给出了您期望的结果,因为NoneType和int之间的无意义比较返回固定值,而与整数值无关。在Python 3中,当你做这样的事情时(比较没有有意义的排序的类型),你会得到一个'TypeError'。 – delnan 2011-06-06 16:11:59
看起来像Python中的不一致,比其他任何东西都重要。 – 2011-06-06 16:12:18
http://stackoverflow.com/questions/2214194/is-everything-greater-than-none – 2011-06-06 16:13:43