Python heapq:拆分并合并成一个有序的heapq

2024-09-28 20:18:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想拆分两个heapq(用作优先级队列),然后将它们添加到一起,并使生成的heapq相对于前两个heapq排序。你知道吗

这在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

Tags: 代码innewforindexlen排序队列
1条回答
网友
1楼 · 发布于 2024-09-28 20:18:05

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

相关问题 更多 >