简体   繁体   English

Python heapq:拆分并合并为有序的heapq

[英]Python heapq: Split and merge into a ordered heapq

I am wanting to split two heapqs (used as a priority queues), and then add them together and have the resulting heapq ordered in relation to both of the previous heapqs. 我想拆分两个heapq(用作优先级队列),然后将它们加在一起,并相对于两个先前的heapq排序得到的heapq。

Is this possible in python? 这可能在python中吗?

My current code: 我当前的代码:

population = []
for i in range(0, 6):
    heappush(population, i)
new_population = []
for i in range(4, 9):
    heappush(new_population, i)

split_index = len(population) // 2
temp_population = population[:split_index]
population = new_population[:split_index] + temp_population
print(population)
print(heappop(population))

Output: 输出:

[4, 5, 6, 0, 1, 2]
4

Wanted output: 想要的输出:

[0, 1, 2, 4, 5, 6]
0

Use nlargest instead of slicing, then reheapify the combined lists. 使用nlargest而不是切片,然后重新组合组合的列表。

from heapq import nlargest, heapify
n = len(population) // 2
population = heapify(nlargest(population, n) +
                     nlargest(new_population, n))
print(heappop(population))

You may want to benchmark, though, if sorting the two original lists, then merging the results, is faster. 但是,如果对两个原始列表进行排序,然后合并结果,则可能会比较方便。 Python's sort routine is fast for nearly sorted lists, and this may impose a lot less overhead than the heapq functions. Python的sort例程对于几乎排序的列表非常快速,这可能会比heapq函数带来更少的开销。 The last heapify step may not be necessary if you don't actually need a priority queue (since you are sorting them anyway). 如果您实际上不需要优先级队列(因为无论如何对它们进行排序),则可能不需要最后一个heapify步骤。

from itertools import islice
from heapq import merge, heapify
n = len(population)  # == len(new_population), presumably
population = heapify(islice(merge(sorted(population), sorted(new_population)), n))

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

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