问题
I wonder how Python decides the order between two items that would be in a tie based on some specified key of a sort. For example, given: l = [[1, 2, 3], [1, 2], [1], [2, 3, 4], [1, 2, 4, 5]]
, how does Python order [1, 2, 3]
and [2, 3, 4]
in this sort:
sorted(l, key=lambda i: len(i), reverse=True)
Does it keep the original (relative) order between items in a tie? Or does it order them randomly?
回答1:
Also in wiki:
Starting with Python 2.2, sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.
回答2:
From the docs:
The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
来源:https://stackoverflow.com/questions/26819012/how-does-python-break-tie-when-sorting-an-iterable