2010-02-19 26 views
16

是否有任何巧妙的內置函數或返回1min()示例如下? (我敢打賭,有它不返回任何一個堅實的理由,但在我的具體情況我需要它無視None值實在太差!)用Python列出Python中的最小值?

>>> max([None, 1,2]) 
2 
>>> min([None, 1,2]) 
>>> 

回答

33

None被返回

>>> print min([None, 1,2]) 
None 
>>> None < 1 
True 

如果你想返回1您必須將None過濾掉:

>>> L = [None, 1, 2] 
>>> min(x for x in L if x is not None) 
1 
+1

注意'None'僅在Python 2.返回在Python 3'分鐘([無,1,2])'產生一個TypeError:'int'和'NoneType'的實例之間不支持'<'。 – 2017-09-26 11:10:39

3

使用生成器表達式:

>>> min(value for value in [None,1,2] if value is not None) 
1 

最終,可以使用過濾器:

>>> min(filter(lambda x: x is not None, [None,1,2])) 
1 
+1

最好是比較身份,然後等於處理'無' – SilentGhost 2010-02-19 10:20:11

+0

你是正確的,糾正。 – 2010-02-19 10:23:19

+2

語法沒有任何python 3.它在python 2中工作得很好。 使用'is'與'None'比較,因爲在'value is not None'中優先使用'=='(或'!=')。帶'filter'的行是**錯誤**,嘗試在列表中輸入0,你會發現它也會被過濾,這不是你想要的。 – nosklo 2010-02-19 10:23:31

相關問題