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

There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various manuals describing them,so I'll do so here.

Sorting Basics【基本排序】

A simple ascending【递增】 sort is very easy -- just call the sorted() function. It returns a new sorted list:

>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

You can also use the list.sort() method of a list. It modifies the list in-place (and returns None to a void confusion). Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient.


>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]

Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted()function accepts any iterable.


>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]

Key Functions【Key 方法】

Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.【自从python2.4之后,list.sort和sorted都添加了一个key参数用来指定一个函数,这个函数作用于每个list元素,在做cmp之前调用】

For example, here's a case-insensitive【不区分大小写】 string comparison:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.This technique is fast because the key function is called exactly once for each input record.


A common pattern is to sort complex objects using some of the object's indices as a key. For example:

>>> student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The same technique works for objects with named attributes. For example:

>>> class Student:
        def __init__(self, name, grade, age):
       = name
                self.grade = grade
                self.age = age
        def __repr__(self):
                return repr((, self.grade, self.age))

>>> student_objects = [
        Student('john', 'A', 15),
        Student('jane', 'B', 12),
        Student('dave', 'B', 10),
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Operator Module Functions【运算符模块方法】

The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter, attrgetter, and starting in Python 2.6 a methodcaller function.

【上述key方法模式在python中是很常用的,所以python提供了方便的函数来更加便捷的访问这个函数,operator模块有itemgetter, attrgetter以及从python2.6出现的methodcaller方法

Using those functions, the above examples become simpler and faster.

>>> from operator import itemgetter, attrgetter

>>> sorted(student_tuples, key=itemgetter(2))【age是student中第2个条目(从0记)】
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(student_objects, key=attrgetter('age'))【直接注明age属性】
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The operator module functions allow multiple levels of sorting.For example, to sort by grade then by age:


>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

Ascending and Descending【递增和递减】

Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is using to flag descending sorts.For example, to get the student data in reverse age order:


>>> sorted(student_tuples, key=itemgetter(2), reverse=True)【递减】
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

>>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

Sort Stability and Complex Sorts【排序的稳定性以及复杂排序

Starting with Python 2.2, sorts are guaranteed to be stable.That means that when multiple records have the same key,their original order is preserved.

>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> sorted(data, key=itemgetter(0))
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]

Notice how the two records for 'blue' retain their original order so that ('blue', 1) is guaranteed to precede ('blue', 2).

This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade:


>>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
>>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The Timsort algorithm(优化后的归并排序) used in Python does multiple sorts efficientlybecause it can take advantage of any ordering already present ina dataset.

The Old Way Using Decorate-Sort-Undecorate【老方法:DSU:装饰-排序-去装饰】

This idiom is called Decorate-Sort-Undecorate after its three steps:

  • First, the initial list is decorated with new values that control the sort order.
  • 【第一步:用一个新值去装饰初始list,这个值就是排序的依据】
  • Second, the decorated list is sorted.
  • 【第二步:对装饰好的list进行排序】
  • Finally, the decorations are removed, creating a list that contains only the initial values in the new order.
  • 【第三步:去除装饰信息,生成一个排好序的只包含初始值的list】

For example, to sort the student data by grade using the DSU approach:


【D】>>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]  【这里好像使用了类似B if A句型?】  
【S】>>> decorated.sort() 【U】>>> [student for grade, i, student in decorated] # undecorate
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]


for item in sequence:
for index in range(len(sequence)):
for index, item in enumerate(sequence):
 process(index, item)

This idiom works because tuples are compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on.


It is not strictly necessary in all cases to include the index iin the decorated list. Including it gives two benefits:

【decorated list中的索引i并不是所有场合都必须的,包含索引之后有两个好处:】

  • The sort is stable - if two items have the same key, their order will be preserved in the sorted list.
  • 【排序是稳定的】
  • The original items do not have to be comparable because the ordering of the decorated tuples will be determined by at most the first two items. So for example the original list could contain complex numbers which cannot be sorted directly.

  • 【初始序列不一定要是可以排序的】

Another name for this idiom is Schwartzian transform, after Randal L. Schwartz, who popularized it among Perl programmers.

For large lists and lists where the comparison informationis expensive to calculate, and Python versions before 2.4, DSU is likely to be the fastest way to sort the list. For 2.4 and later, key functions provide the same functionality.


The Old Way Using the cmp Parameter【老方法:使用cmp参数】

Many constructs【架构】 given in this HOWTO assume Python 2.4 or later. Before that, there was no sorted() built in and list.sort() took no keyword arguments. Instead, all of the Py2.x versions supported a cmp parameter to handle user specified comparison functions.

In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__methods).


In Py2.x, sort allowed an optional function which can be called for doing thecomparisons. That function should take two arguments to be compared andthen return a negative value for less-than, return zero if they are equal,or return a positive value for greater-than. For example, we can do:


>>> def numeric_compare(x, y):
        return x - y
>>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
[1, 2, 3, 4, 5]

Or you can reverse the order of comparison with:

>>> def reverse_numeric(x, y):
        return y - x
>>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
[5, 4, 3, 2, 1]

When porting【移植】 code from Python 2.x to 3.x, the situation can arisewhen you have the user supplying a comparison function and youneed to convert that to a key function. The following wrappermakes that easy to do:

def cmp_to_key(mycmp): 【从2.x到3.x移植程序时需要用到】
    'Convert a cmp= function into a key= function'
    class K(object):
        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 2.7, the cmp_to_key() tool was added to the functools module.

Odd and Ends【其他方法、结尾】

  • For locale aware sorting, use locale.strxfrm() for a key function or locale.strcoll() for a comparison function.

  • 【locale是什么东东?】
  • The reverse parameter still maintains sort stability (i.e. records with equal keys retain the original order). Interestingly, that effect can be simulated without the parameter by using the builtin reversedfunction twice:


    • >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
      >>> assert sorted(data, reverse=True) == list(reversed(sorted(reversed(data))))【断言,判断是否为真】
  • To create a standard sort order for a class, just add the appropriate rich comparison methods:
  • 为一个类创建基本排序方法时候,只需要这样。
  • >>> Student.__eq__ = lambda self, other: self.age == other.age
    >>> Student.__ne__ = lambda self, other: self.age != other.age
    >>> Student.__lt__ = lambda self, other: self.age < other.age
    >>> Student.__le__ = lambda self, other: self.age <= other.age
    >>> Student.__gt__ = lambda self, other: self.age > other.age
    >>> Student.__ge__ = lambda self, other: self.age >= other.age
    >>> sorted(student_objects)
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    For general purpose comparisons, the recommended approach is to define all six rich comparison operators. The functools.total_ordering class decorator makes this easy to implement.

  • Key functions need not access data internal to objects being sorted. A key function can also access external resources. For instance, if the student grades are stored in a dictionary, they can be used to sort a separate list of student names:
  • key函数不仅可以通过对象内部数据进行排序,也可以通过访问外部资源。例如,学生grades存储在一个字典中,可以使用他们对一个单独的学生姓名list进行排序
    • >>> students = ['dave', 'john', 'jane']
      >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}
      >>> sorted(students, key=newgrades.__getitem__)
      ['jane', 'dave', 'john']
  • Alternate data structure for performance with ordered data
  • 【为了有序数据的更好操作,可以灵活选择数据结构】
  •   If you're needing a sorted list every step of the way as you process each item to be added to the sorted list, then list.sort(), sorted() and bisect.insort() are all very slow and tend to yield quadratic behavior【二次行为?】 or worse. In such a scenario, it's better to use something like a heap, red-black tree or treap (like the included heapq module, or this treap module - shameless plug added by python treap module author).
  • 【如果你想要每添加一个item之后都对list进行排序,list.sort、sorted以及bisect.insort的效率都很低而且容易出错,这时,使用其他的数据结构:heap堆、red-black tree红黑树或者treap树堆(在heapq模块或者treap模块中)】
posted @ 2012-11-04 23:17 ZH奶酪 阅读(...) 评论(...) 编辑 收藏