summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Doc/howto/sorting.rst21
1 files changed, 17 insertions, 4 deletions
diff --git a/Doc/howto/sorting.rst b/Doc/howto/sorting.rst
index 746e40c0bd..acdf3ab086 100644
--- a/Doc/howto/sorting.rst
+++ b/Doc/howto/sorting.rst
@@ -111,6 +111,15 @@ sort by *grade* then by *age*:
>>> 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 @@ Odd and Ends
* 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 @@ Odd and Ends
>>> 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']