2017-05-09 58 views
-1

你能解釋一下這個python代碼嗎? (樂趣)`工作?如何在Python中對sort函數進行工作cmp參數

def fun(a, b): 
    return cmp(a[1], b[1]) 

L= [[2, 1], [4, 5, 3]] 
L.sort(fun) 
print L 
+0

是不是自我解釋,所有的解釋可以通過搜索python的文檔找到。即使可能甚至在這裏http://stackoverflow.com/documentation/python/809/incompatibilities-moving-from-python-2-to-python-3/6139/cmp-function-removed-in-python-3#t= 201705091116364415354 –

回答

0

從官方文檔:

The sort() method takes optional arguments for controlling the comparisons. 

cmp specifies a custom comparison function of two arguments (list items) 
which should return a negative, zero or positive number depending on whether 
the first argument is considered smaller than, equal to, or larger than the 
second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). 
The default value is None. 

所以,你試圖控制使用自己的函數「好玩」的比較。比較列表中列表的第一個索引處的值(嵌套列表)。 如果您嘗試單獨測試,您將得到-1,因爲a [1]明顯小於b [1]
,因此輸出爲「[[2,1],[4,5,3]] 「已經排序

a = [2,1] 
b = [4,5,3] 
cmp(a[1], b[1]) 

你可以嘗試改變第一個索引的值,就像這樣,你就會明白它是如何工作的。

像這樣的事情

def fun(a,b): 
    return cmp(a[1], b[1]) 
L=[[2,6],[4,5,3]] 
L.sort(fun) 
print L 

我希望這將有助於。

+0

當我使用L = [1,2,3,4]時我收到一條錯誤消息,爲什麼? –

+0

@SelvakumarAnushan:是的,因爲那樣它就不會被嵌套列表。如果L = [1,2,3,4] a [1]和b [1]沒有意義 –

相關問題