我想執行以下操作:的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