最近在看<<Python基础编程>>,里面第二章(列表和元组)里,有一段关于高级排序的讲解
原文:
如果希望元素能按照特定的方式进行排序(而不是sort函数默认的方式,即根据python的默认排序规则按升序排列元素),那么可以通过compare(x,y)形式自定义比较函数。
compare(x,y)函数会在x<y时返回负数,在x>y时返回正数,如果x=y则返回0(根据你的定义)。定义好该函数之后,就可以提供给sort方法作为参数了。内建函数cmp提供了比较函数的默认实现方式:
>>> 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作为sort的参数,numbers的输出都是一样的嘛,那,需要cmp参数干些什么呢在sort的方法里。
请大家帮忙回答一下,谢谢。
sort
For the complete definition of parameters, see:http://docs.python.org/2/library/functions.html#sorted
https://wiki.python.org/moin/HowTo /Sorting/
If I want to sort in descending order, then I need to customize the cmp method (of course the more convenient one is numbers.sort(reverse=True))
If the array member is not a number, but another type such as dict, and you want to sort it based on a certain attribute
In fact, when the sort() method does not pass in the parameter func, the default cmp is None.
What is called is
lambda x,y: cmp(x, y)
, but it actually calls the cmp function. That is:If you want to implement a custom comparison function, you need to re-specify the comparison function constructed by cmp for you, as follows:
In addition, the cmp parameter has been canceled in python3.x, and it is no longer supported to directly pass functions into sort(). You can construct a sorting function and pass it to the key.
Python List sort() method application: http://www.w3cschool.cc/python/att-list-sort.html