这很有趣; 使用list()
强制将迭代器转换为实际列表的速度比使用推导式[x for x in someList]
快得多。
这是真实情况还是我的测试太简单了?以下是代码:
import time
timer = time.clock()
for i in xrange(90):
#localList = [x for x in xrange(1000000)] #Very slow, took me 6.8s
localList = list(xrange(1000000)) #Very fast, took me 0.9s
print localList[999999] #make sure list is really evaluated.
print "Total time: ", time.clock() - timer
timeit
计时得到了5.5秒,而Python 3.6则只用了3.6秒。 - user