为什么在两个语句中获得字典的前30个键比一个语句要快?

我正在为自己做一个基准测试,发现我遇到了这个有趣的事情。我正在尝试获取字典的前30个键,并且我编写了三种获取方法,如下所示:

import time
dic = {str(i): i for i in range(10 ** 6)}

start_time = time.time()
x = list(dic.keys())[0:30]
print(time.time() - start_time)

start_time = time.time()
y = list(dic.keys())
x = y[0:30]
print(time.time() - start_time)

start_time = time.time()
z = dic.keys()
y = list(z)
x = y[0:30]
print(time.time() - start_time)

结果是:

0.015970945358276367   0.010970354080200195   0.01691460609436035

令人惊讶的是,第二种方法要快得多!有什么想法吗?

评论