[Python-checkins] bpo-35020: Link to sorting examples from list.sort() (GH-9931)
Raymond Hettinger
webhook-mailer at python.org
Sat Oct 20 17:39:06 EDT 2018
https://github.com/python/cpython/commit/890a4b92933be8e7c554222d99ef829c88fa8637
commit: 890a4b92933be8e7c554222d99ef829c88fa8637
branch: master
author: Xtreak <tirkarthi at users.noreply.github.com>
committer: Raymond Hettinger <rhettinger at users.noreply.github.com>
date: 2018年10月20日T14:39:03-07:00
summary:
bpo-35020: Link to sorting examples from list.sort() (GH-9931)
files:
M Doc/howto/sorting.rst
M Doc/library/stdtypes.rst
diff --git a/Doc/howto/sorting.rst b/Doc/howto/sorting.rst
index 128044662899..b2fccb19f5d4 100644
--- a/Doc/howto/sorting.rst
+++ b/Doc/howto/sorting.rst
@@ -145,6 +145,17 @@ ascending *age*, do the *age* sort first and then sort again using *grade*:
>>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
+This can be abstracted out into a wrapper function that can take a list and
+tuples of field and order to sort them on multiple passes.
+
+ >>> def multisort(xs, specs):
+ ... for key, reverse in reversed(specs):
+ ... xs.sort(key=attrgetter(key), reverse=reverse)
+ ... return xs
+
+ >>> multisort(list(student_objects), (('grade', True), ('age', False)))
+ [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
+
The `Timsort <https://en.wikipedia.org/wiki/Timsort>`_ algorithm used in Python
does multiple sorts efficiently because it can take advantage of any ordering
already present in a dataset.
@@ -246,7 +257,7 @@ To convert to a key function, just wrap the old comparison function:
.. testsetup::
- from functools import cmp_to_key
+ >>> from functools import cmp_to_key
.. doctest::
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index d0d5c6157290..01fb5d5e15cd 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -1201,6 +1201,8 @@ application).
--- this is helpful for sorting in multiple passes (for example, sort by
department, then by salary grade).
+ For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
+
.. impl-detail::
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
.. [5] To format only a tuple you should therefore provide a singleton tuple whose only
element is the tuple to be formatted.
-
More information about the Python-checkins
mailing list