How does Python break tie when sorting an iterable

核能气质少年 提交于 2020-01-16 20:28:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!