简体   繁体   English

有效的方式在运行中按升序和降序排序

[英]efficient way to sort in ascending and descending order on the fly

From the following code, I am using the function generator which creates random numbers and helps to simulate incoming data. 从下面的代码中,我使用函数generator创建随机数并帮助模拟传入数据。

from random import randint


def generator(n=1000):
    i = 0
    while i < n:
        yield randint(0, n)
        i += 1

For sorting in ascending order and get only the lowest 10 records I use this: 为了按升序排序并且只获得最低的10条记录,我使用这个:

out_size = 10
out = []
for num in generator():
    if not len(out):
        out.append(num)
    else:
        for i in range(out_size):
            if num < out[i]:
                out.insert(i, num)
                break
            elif len(out) < out_size:
                out.append(num)
                break

print out[:out_size]

Is there an efficient and better way to sort the generated data?, how to doing in descending order. 是否有一种有效且更好的方法来对生成的数据进行排序?如何按降序排序。 ?

The input is a constant stream, but I just need to keep the lowest and highest 10 records. 输入是一个恒定的流,但我只需要保持最低和最高的10条记录。

Use the heapq.nlargest() and heapq.nsmallest() functions; 使用heapq.nlargest()heapq.nsmallest()函数; these use a heap to efficiently track largest or smallest K items for you: 这些使用堆来有效地跟踪最大或最小的K项:

import heapq

out = heapq.nsmallest(10, generator())

A heap invariant is maintained in O(logK) complexity, with K being the size (10 here); 堆不变量以O(logK)复杂度维护,K为大小(此处为10); the nsmallest function creates a heap of size K, fills it with the first K elements, then pushes each next value onto the heap popping off the now-largest each time, in one operation. nsmallest函数创建一个大小为K的堆,用前K个元素填充它,然后在一次操作中将每个下一个值推送到每次弹出当前最大值的堆上。

Looping over N elements then makes the total operation O(N logK), while sorting would take O(N logN). 循环N个元素然后使总操作O(N logK),而排序将采用O(N logN)。 Provided K remains smaller than N the heapq approach wins. 如果K仍然小于N,则heapq方法获胜。

Once the generator is exhausted, the heap is returned in sorted order. 生成器耗尽后,堆将按排序顺序返回。

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

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