小编Lio*_*Box的帖子

高效的列表排序:使用堆代替标准排序速度较慢

我正在尝试创建一种更有效的方法来对 python 中的列表和字典进行排序,并遇到了Efficient data Structurekeepingingobjectsonmultiplekeys。建议的解决方案是使用heapq模块。

然而,在我的测试中,堆似乎比原生 Python 排序算法慢两倍。下面是我用来做简单测试的代码。结果例如:

堆: 0.005993366241455078

标准: 0.0020036697387695312

有没有办法真正使用堆并提高性能,正如上面链接的帖子声称的那样?该代码会是什么样子?

这是测试它的代码:

import  random
import time
from heapq import *

standardlist = []
heaplist = []
for i in range(10000):
    num = random.randint(0,10000)
    standardlist.append(num)
    heappush(heaplist, num)

# Standard sorting method:
start_time = time.time()
sorted_list = sorted(standardlist)
finish_time_1 = time.time() - start_time

# Heap sorting method:
start_time = time.time()
heap_sorted_list = [heappop(heaplist) for i in range(len(heaplist))]
finish_time_2 = time.time() - start_time

print("Standard Finish Time:", finish_time_1) …
Run Code Online (Sandbox Code Playgroud)

python sorting heap performance list

1
推荐指数
1
解决办法
98
查看次数

标签 统计

heap ×1

list ×1

performance ×1

python ×1

sorting ×1