Skip to content

Commit 890a4b9

Browse files
tirkarthirhettinger
authored andcommitted
bpo-35020: Link to sorting examples from list.sort() (pythonGH-9931)
1 parent eeab510 commit 890a4b9

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

Doc/howto/sorting.rst

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,17 @@ ascending *age*, do the *age* sort first and then sort again using *grade*:
145145
>>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending
146146
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
147147

148+
This can be abstracted out into a wrapper function that can take a list and
149+
tuples of field and order to sort them on multiple passes.
150+
151+
>>> def multisort(xs, specs):
152+
... for key, reverse in reversed(specs):
153+
... xs.sort(key=attrgetter(key), reverse=reverse)
154+
... return xs
155+
156+
>>> multisort(list(student_objects), (('grade', True), ('age', False)))
157+
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
158+
148159
The `Timsort <https://en.wikipedia.org/wiki/Timsort>`_ algorithm used in Python
149160
does multiple sorts efficiently because it can take advantage of any ordering
150161
already present in a dataset.
@@ -246,7 +257,7 @@ To convert to a key function, just wrap the old comparison function:
246257

247258
.. testsetup::
248259

249-
from functools import cmp_to_key
260+
>>> from functools import cmp_to_key
250261

251262
.. doctest::
252263

Doc/library/stdtypes.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1201,6 +1201,8 @@ application).
12011201
--- this is helpful for sorting in multiple passes (for example, sort by
12021202
department, then by salary grade).
12031203

1204+
For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
1205+
12041206
.. impl-detail::
12051207

12061208
While a list is being sorted, the effect of attempting to mutate, or even
@@ -4752,4 +4754,3 @@ types, where they are relevant. Some of these are not reported by the
47524754
47534755
.. [5] To format only a tuple you should therefore provide a singleton tuple whose only
47544756
element is the tuple to be formatted.
4755-

0 commit comments

Comments
 (0)