diff options
author | Xtreak <tirkarthi@users.noreply.github.com> | 2018-10-20 21:39:03 (GMT) |
---|---|---|
committer | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2018-10-20 21:39:03 (GMT) |
commit | 890a4b92933be8e7c554222d99ef829c88fa8637 (patch) | |
tree | 3f3d4167ad2e0070016b603d27d2e311e0cc04ec /Doc/howto | |
parent | eeab510bb7e51802c18b3770cbb23ae0ca91da6b (diff) | |
download | cpython-890a4b92933be8e7c554222d99ef829c88fa8637.zip cpython-890a4b92933be8e7c554222d99ef829c88fa8637.tar.gz cpython-890a4b92933be8e7c554222d99ef829c88fa8637.tar.bz2 |
bpo-35020: Link to sorting examples from list.sort() (GH-9931)
Diffstat (limited to 'Doc/howto')
-rw-r--r-- | Doc/howto/sorting.rst | 13 |
1 files changed, 12 insertions, 1 deletions
diff --git a/Doc/howto/sorting.rst b/Doc/howto/sorting.rst index 1280446..b2fccb1 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:: |