>>> 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.
.. testsetup::
- from functools import cmp_to_key
+ >>> from functools import cmp_to_key
.. doctest::
--- 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
.. [5] To format only a tuple you should therefore provide a singleton tuple whose only
element is the tuple to be formatted.
-