[Python-checkins] cpython (2.7): A number of small fixups for the sorting howto guide.
raymond.hettinger
python-checkins at python.org
Tue Jul 19 10:35:43 CEST 2011
http://hg.python.org/cpython/rev/df639f5b1fe8
changeset: 71421:df639f5b1fe8
branch: 2.7
parent: 71417:c4d884d5d86c
user: Raymond Hettinger <python at rcn.com>
date: Tue Jul 19 01:35:35 2011 -0700
summary:
A number of small fixups for the sorting howto guide.
files:
Doc/howto/sorting.rst | 21 +++++++++++++++++----
1 files changed, 17 insertions(+), 4 deletions(-)
diff --git a/Doc/howto/sorting.rst b/Doc/howto/sorting.rst
--- a/Doc/howto/sorting.rst
+++ b/Doc/howto/sorting.rst
@@ -111,6 +111,15 @@
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
+The :func:`operator.methodcaller` function makes method calls with fixed
+parameters for each object being sorted. For example, the :meth:`str.count`
+method could be used to compute message priority by counting the
+number of exclamation marks in a message:
+
+ >>> messages = ['critical!!!', 'hurry!', 'standby', 'immediate!!']
+ >>> sorted(messages, key=methodcaller('count', '!'))
+ ['standby', 'hurry!', 'immediate!!', 'critical!!!']
+
Ascending and Descending
========================
@@ -259,8 +268,8 @@
* For locale aware sorting, use :func:`locale.strxfrm` for a key function or
:func:`locale.strcoll` for a comparison function.
-* The *reverse* parameter still maintains sort stability (i.e. records with
- equal keys retain the original order). Interestingly, that effect can be
+* The *reverse* parameter still maintains sort stability (so that records with
+ equal keys retain their original order). Interestingly, that effect can be
simulated without the parameter by using the builtin :func:`reversed` function
twice:
@@ -275,12 +284,16 @@
>>> 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 :func:`functools.total_ordering` class
+ decorator makes this easy to implement.
+
* Key functions need not depend directly on the 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:
>>> students = ['dave', 'john', 'jane']
- >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}
- >>> sorted(students, key=newgrades.__getitem__)
+ >>> grades = {'john': 'F', 'jane':'A', 'dave': 'C'}
+ >>> sorted(students, key=grades.__getitem__)
['jane', 'dave', 'john']
--
Repository URL: http://hg.python.org/cpython
More information about the Python-checkins
mailing list