Python3 sort and sorted

2017-01-10 10:05:02来源:oschina作者:codetask人点击

第七城市

Python lists have a built-inlist.sort()method that modifies the list in-place. There is also asorted()built-in function that builds a new sorted list from an iterable.


list类的內建sort方法会直接排序修改自身, 而sorted函数将会返回一个新的已排序的list


In Py3.0, thecmpparameter was removed entirely


并且已经去掉了cmp参数字段


当然,3里要实现cmp参数也是可以的


When porting code from Python 2.x to 3.x, the situation can arise when you have the user supplying a comparison function and you need to convert that to a key function. The following wrapper makes that easy to do:


def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K

To convert to a key function, just wrap the old comparison function:


>>>


>>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
[5, 4, 3, 2, 1]

In Python 3.2, thefunctools.cmp_to_key()function was added to thefunctoolsmodule in the standard library.


这里的 cmp_to_key() 将函数包装成一个类, 这个类可以接受一个参数,并且重载了常用的操作符.

第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台