http://wiki.python.org/moin/HowTo/Sorting/
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.
【sorted返回一個新的list,sort在原list基礎上進行修改】
>>> 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可以對任意iterable排序,sort只能對list排序】
>>> 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.
【key參數是一個函數,這個函數有一個參數,返回一個用來排序的關鍵字。這個技術很快,因為key方法在每個輸入的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): self.name = name self.grade = grade self.age = age def __repr__(self): return repr((self.name, 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:
【operator模塊函數支持多級排序,例如先按grade再按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:
【sort和sorted中的reverse(布爾值)參數用來標記排序順序的,True-遞減,False-遞增(默認)】
>>> 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:
【要想結果是先按grade遞減排序,再按age遞增排序。那么,程序中就要先對age進行排序,再按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:
【用DSU方法對student按照grade排序】
【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)]
【enumerate(枚舉)是做什么用的???】
附:在Python中,我們習慣這樣遍歷:
for item in sequence:
process(item)
這樣遍歷取不到item的序號i,所有就有了下面的遍歷方法:
for index in range(len(sequence)):
process(sequence[index])
其實,如果你了解內置的enumerate函數,還可以這樣寫:
for index, item in enumerate(sequence):
process(index, item)
詳細出處參考:http://www.jb51.net/article/15715.htm
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.
【這個方法之所以起作用,是因為tuples是按照字典序比較的,比較第1項,如果相同,就比較第2項,以此類推】
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.
【python2.4之前,這個方法是最快的排序list方法,但是之后的key函數提供了同樣的效果。】
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).
【python3.0之后已經完全移除了cmp參數】
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:
【直接看下邊代碼就知道cmp怎么回事了】
>>> 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:
reverse參數依然維持排序穩定性。有趣的是,這個效果可以通過不使用這個參數而使用內置reverse方法兩次來驗證。
-
>>> 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模塊中)】