python中排序函数的cmp参数如何工作

python中排序函数的cmp参数如何工作,python,Python,你能解释一下这个python代码吗? 这里L.sort(fun)`如何工作 从官方文件: 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 numbe

你能解释一下这个python代码吗?

这里
L.sort(fun)`如何工作


从官方文件:

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.
因此,您试图使用自己的函数“fun”来控制比较。这表示比较列表(嵌套列表)中列表的第一个索引处的值。 如果您尝试单独测试它,您将得到-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

我希望这会有所帮助。

当我使用L=[1,2,3,4]时,我收到一条错误消息,为什么?@SelvakumarAnushan:是的,因为这样它就不会是嵌套列表。在L=[1,2,3,4]的情况下,a[1]和b[1]没有意义,这不是不言自明的,所有解释都可以通过搜索python文档找到。甚至可能在这里
def fun(a,b):
    return cmp(a[1], b[1])
L=[[2,6],[4,5,3]]
L.sort(fun)
print L