python 的 sorted() 函数是否保证稳定? [英] Is python's sorted() function guaranteed to be stable?

查看:61
本文介绍了python 的 sorted() 函数是否保证稳定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档 并不能保证这一点.有没有其他地方记录它?

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% 清楚这个身份;文档补丁总是被愉快地接受!

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆