python的sorted()函数是否保证稳定? [英] Is python's sorted() function guaranteed to be stable?
问题描述
文档不能保证这一点.还有其他记录在案的地方吗?
The documentation doesn't guarantee that. Is there any other place that it is documented?
我猜想它可能是稳定的,因为列表上的排序方法是保证是稳定的(注意第9点:从Python 2.3开始,保证sort()方法是稳定的"),并且sorted在功能上相似.但是,我找不到任何明确的说法.
I'm guessing it might be stable since the sort method on lists is guaranteed to be stable (Notes 9th point: "Starting with Python 2.3, the sort() method is guaranteed to be stable"), and sorted is functionally similar. However, I'm not able to find any definitive source that says so.
目的:在两个记录中主键相等的情况下,我需要基于主键和辅助键进行排序.如果保证sorted()是稳定的,那么我可以对辅助键进行排序,然后对主键进行排序,并获得所需的结果.
Purpose: I need to sort based on a primary key and also a secondary key in cases where the primary key is equal in both records. If sorted() is guaranteed to be stable, I can sort on the secondary key, then sort on the primary key and get the result I need.
PS:为避免引起混淆,我使用稳定"的含义是排序是稳定的,如果它保证不更改比较相等的元素的相对顺序".
PS: To avoid any confusion, I'm using stable in the sense of "a sort is stable if it guarantees not to change the relative order of elements that compare equal".
推荐答案
是的,该手册的目的确实是为了确保sorted
是稳定的,并且确实使用与sort
方法完全相同的算法.我的确意识到这些文件并不是100%清楚.总是很高兴地接受doc补丁!
Yes, the intention of the manual is indeed to guarantee that sorted
is stable and indeed that it uses exactly the same algorithm as the sort
method. I do realize that the docs aren't 100% clear about this identity; doc patches are always happily accepted!
这篇关于python的sorted()函数是否保证稳定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!