我想拆分两个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
使用
nlargest
而不是切片,然后重新调整组合列表。你知道吗不过,如果对两个原始列表进行排序,然后合并结果,则可能需要进行基准测试,这样会更快。Python的
sort
例程对于几乎排序的列表是快速的,这可能会比heapq
函数带来更少的开销。如果您实际上不需要优先级队列,那么最后一步heapify
可能是不必要的(因为您正在对它们进行排序)。你知道吗相关问题 更多 >
编程相关推荐