Python集合排序,为什么这么快?

标签 python sorting

为什么Python内置的sorted对集合的排序如此之快?

我的意思是,速度快得令人难以置信,我将它与一组 80000 个条目一起使用,并且花费的时间非常非常短(0.0 是 time.clock() 差异的输出)。 这是某种优化吗?

集合内的记录是否已排序?

顺便问一下,集合的排序是如何实现的?能给我代码吗?

最佳答案

没有什么特殊的魔力:排序是用 C 实现的,效率很高。 time.clock 并不是对 Python 代码进行基准测试的理想方法,因为在某些平台上其输出的分辨率可能非常低。为了获得最佳结果,请使用 timeit 模块来测量耗时。

也没有特殊的算法来对集合进行排序。当在 set(或其他任何东西)上调用时,sorted 内置函数的作用相当于:

def sorted(iterable):
    templist = list(iterable)
    templist.sort()
    return templist

所以,真正的魔力是 in the list.sort method 。 (详细解释了实现 in the adjacent file. )

关于Python集合排序,为什么这么快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22551635/

相关文章:

python - 将 pcollection 的每一行拆分为多个 pcollection?

python - scikit-learn:ImportError:无法导入名称 atleast2d_or_csr

javascript - AngularJS ng-repeat orderby 无法正确处理希腊单词

java - 快速排序三中位数

python - Scrapy 中的验证码

python - 正则表达式从函数中提取表达式?

c++ - 我的 C++ 合并排序程序有什么问题?

c# - 在 C# 中使用多个条件和多个变量对列表进行排序

python - pickle UnicodeDecodeError

python - 如何在 Python 中将字典值转换为 int?