Python中的全局sorted函数

来源:互联网 发布:一公升的眼泪 知乎 编辑:程序博客网 时间:2024/06/11 22:35

sorted函数
Python内置的排序函数sorted可以对list或者iterator进行排序,官网文档见:http://docs.python.org/2/library/functions.html?highlight=sorted#sorted
函数定义为:sorted(iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable.

The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section Mutable Sequence Types).

cmp specifies a custom comparison function of two arguments (iterable elements) 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.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

For sorting examples and a brief sorting tutorial, see Sorting HOW TO.

eg: 对每个人按第三项年龄升序排序
stu=[(‘nami’, ‘c’, 15), (‘luffy’, ‘b’, 18), (‘zoro’, ‘a’, 22)]
sorted(stu, cmp=lambda a,b:a-b, key=operator.itemgetter(2))
函数有三个参数:
1、iterable:指定要排序的list或者iterable,iterable可以是自定义的
2、cmp:接受一个函数(有两个参数),指定排序时进行比较的函数,可以指定一个函数或lambda表达式。当上面的例子中,cmp=lambda a,b:b-a时,会是降序排序
3、key:接受一个函数(多个参数时是多级排序),指定待排序元素的哪一项进行排序。key可以时lambda表达式。如:
sorted(stu, cmp=lambda a,b:a-b, key=lambda stu:stu[2])

阅读全文
0 0