简体   繁体   English

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

[英]Python set sorted, Why so fast?

Why is Python built-in sorted on a set is so fast? 为什么在sortedsorted Python内置如此之快?

I mean, incredibly fast, I used it with a set of 80000 entries and it takes very very short time (0.0 is the output of the time.clock() difference). 我的意思是,非常快,我使用了一组80000条目,它需要非常短的时间(0.0是time.clock()差异的输出)。 Is that some kind of optimization? 这是某种优化吗?

Are the records already sorted inside the set? 记录是否已在集合内排序?

And, by the way, how is sorted for set implemented? 顺便说一下,如何对集合进行排序? Can you give me the code? 你能给我代码吗?

There is no special magic: the sorting is implemented in C, efficiently. 没有特别的魔力:排序是在C中有效实现的。 time.clock is not the ideal way to benchmark Python code, since the resolution of its output can be quite low on some platforms. time.clock不是对Python代码进行基准测试的理想方法,因为在某些平台上,其输出的分辨率可能非常低。 For best results, use the timeit module to measure elapsed time. 为获得最佳效果,请使用timeit模块测量经过的时间。

There is also no special algorithm to sort sets. 排序集也没有特殊的算法。 The sorted built-in, when called on a set (or anything else, for that matter) does the equivalent of: sorted内置函数在set (或其他任何东西)上调用时,相当于:

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

So, the real magic is in the list.sort method . 所以,真正的魔力在于list.sort方法 (The implementation is explained in some detail in the adjacent file. ) 相邻文件中详细解释了实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM