python中sort()方法的cmp参数

《python基础编程》里有讲到一段高级排序:python

  “若是但愿元素能按照特定的方式进行排序(而不是sort函数默认的方式,即根据python的默认排序规则按升序排列元素,第5章内对此进行讲解),那么能够经过compare(x,y)的形式自定义比较函数。compare(x,y)函数会在x<y时返回负数,在x>y时返回正数,若是x=y则返回0(根据你的定义)。定义好该函数以后,就能够提供给sort方法做为参数了。内建函数cmp提供了比较函数的默认实现方式:shell

>>>cmp(42,32)
1
>>>cmp(99,100)
-1
>>>cmp(10,10)
0
>>>numbers = [5,2,9,7]
>>>numbers.sort(cmp)
>>>numbers
[2,5,7,9]

"编程

对于sort()方法,若是不传入参数,默认cmp为None,即numbers.sort()=number,sort(cmp)=number.sort(cmp=None),咱们能够作一个验证:python3.x

 

>>> numbers = [5,2,9,7]
>>> numbers.sort()
>>> numbers
[2, 5, 7, 9]函数


>>> numbers = [5,2,9,7]
>>> numbers.sort(cmp)
>>> numbers
[2, 5, 7, 9]spa


>>> numbers = [5,2,9,7]
>>> numbers.sort(cmp=None)
>>> numbers
[2, 5, 7, 9]
>>> code

 

若是传入参数,numbers.sort(cmp=1),咱们能够验证一下,整型的参数可不能够:对象

>>> numbers = [5,2,9,7]
>>> numbers.sort(cmp=1)

Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    numbers.sort(cmp=1)
TypeError: 'int' object is not callable
>>> 

代码报错:int对象不是一个callable,可调用对象。callable(object) 方法用来检测对象是否可被调用,便是否是一个函数,若是是则调用该函数的值,赋值给cmp。blog

那么咱们如何自定义一个比较函数呢?排序

def mycmp1(x,y):  #升序排列
    return x-y
def mycmp2(x,y): #降序排列
    return y-x

其中的规律就是:两两比较,若是返回为正,则交换二者的位置,即y在前x在后,不然x在前y在后。也能够这样解释,升序就是拿第一个数比对后面的数,降序就是拿最后一个数比对前面的数。

#升序排列
numbers = [5,2,9,7]
def mycmp1(x,y):
        return x-y
numbers.sort(cmp = mycmp1)
print numbers

>>>
[2, 5, 7, 9]

#降序排列
numbers = [5,2,9,7]
def mycmp2(x,y):
        return y-x
numbers.sort(cmp = mycmp2)
print numbers

>>>
[9,7,5,2]

固然,也能够写做numbers.sort(mycmp1),省略cmp。

咱们还能够直接穿入匿名函数lambda:

#升序排列
numbers = [5,2,9,7]
numbers.sort(cmp = lambda x,y: x-y)
print numbers

>>>
[2,5,7,9]

#降序排列
numbers = [5,2,9,7]
numbers.sort(cmp = lambda x,y: y-x)
print numbers

>>>
[9,7,5,2]

另外,python3.x中取消了cmp参数,也不支持直接往sort()里面传函数,但能够构造排序函数传递给key来实现。

相关文章
相关标签/搜索