Python heapq:拆分并合并到有序的heapq中

时间:2018-03-19 14:32:23

标签: python heap priority-queue

我想要拆分两个heapqs(用作优先级队列),然后将它们一起添加,并将结果heapq与前两个heapqs相关联。

这在python中可行吗?

我目前的代码:

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))

输出:

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

通缉输出:

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

1 个答案:

答案 0 :(得分:0)

使用nlargest代替切片,然后重新合并组合列表。

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

但是,您可能想要进行基准测试,如果对两个原始列表进行排序,然后合并结果,则会更快。对于几乎排序的列表,Python的sort例程速度很快,这可能会比heapq函数带来更少的开销。如果您实际上不需要优先级队列,则可能不需要最后一个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))