[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Although these examples serve an educational role, built-in lists and functions generally
accomplish what we just did the hard way:


Built-in sorting tools
Python’s two built-in sorting tools are so fast that you would be hard-pressed to
beat them in most scenarios. To use the list object’s sort method for arbitrary kinds
of iterables, convert first if needed:
temp = list(sequence)
temp.sort()
...use items in temp...
Alternatively, the sorted built-in function operates on any iterable so you don’t
need to convert, and returns a new sorted result list so you can use it within a larger
expression or context. Because it is not an in-place change, you also don’t need to
be concerned about the possible side effects of changing the original list:
for item in sorted(iterable):
...use item...
For custom sorts, simply pass in the key keyword arguments to tailor the built-in
sort’s operation—it maps values to sort keys instead of performing comparisons,
but the effect is just as general (see the earlier graph searchers’ length ordering for
another example):





L = [{'n':3}, {'n':20}, {'n':0}, {'n':9}]
L.sort(key=lambda x: x['n'])
L
[{'n': 0}, {'n': 3}, {'n': 9}, {'n': 20}]
Both sorting tools also accept a Boolean reverse flag to make the result order de-
scending instead of ascending; there is no need to manually reverse after the sort.
The underlying sort routine in Python is so good that its documentation claims
that it has “supernatural performance”—not bad for a sort.





Built-in reversal tools
Our reversal routines are generally superfluous by the same token—because Py-
thon provides for fast reversals in both in-place and iterable forms, you’re likely
better off using them whenever possible:





L = [2, 4, 1, 3, 5]
L.reverse()
L
[5, 3, 1, 4, 2]





>>> L = [2, 4, 1, 3, 5]
>>> list(reversed(L))
[5, 3, 1, 4, 2]

In fact, this has been a recurring theme of this chapter on purpose, to underscore a key
point in Python work: although there are plenty of exceptions, you’re generally better


Reversing and Sorting Sequences| 1401
Free download pdf