最佳答案
复制一个打乱的 range(10**6)
列表需要大约0.18秒: (这是5次运行)
0.175597017661
0.173731403198
0.178601711594
0.180330912952
0.180811964451
复制未洗涤的列表10次大约需要0.05秒:
0.058402235973
0.0505464636856
0.0509734306934
0.0526022752744
0.0513324916184
这是我的测试代码:
from timeit import timeit
import random
a = range(10**6)
random.shuffle(a) # Remove this for the second test.
a = list(a) # Just an attempt to "normalize" the list.
for _ in range(5):
print timeit(lambda: list(a), number=10)
我也试过用 a[:]
复制,结果是相似的(也就是说,速度差异很大)
为什么速度差这么大?我知道并理解著名的 为什么处理排序的数组比处理未排序的数组更快?示例中的速度差异,但在这里我的处理没有决策。它只是盲目地复制列表中的引用,不是吗?
我在 Windows 10上使用 Python 2.7.12。
编辑: 现在也尝试了 Python 3.5.2,结果几乎相同(一直在0.17秒左右洗牌,一直在0.05秒左右取消洗牌)。下面是代码:
a = list(range(10**6))
random.shuffle(a)
a = list(a)
for _ in range(5):
print(timeit(lambda: list(a), number=10))