当使用Python的
下面是使用
random.shuffle
函数时,我注意到使用sorted(l, key=lambda _: random.random())
比random.shuffle(l)
更快。据我所知,两种方法都可以产生完全随机的列表,那么为什么shuffle
需要花费更多时间呢?下面是使用
timeit
模块计时的结果。from timeit import timeit
setup = 'import random\nl = list(range(1000))'
# 5.542 seconds
print(timeit('random.shuffle(l)', setup=setup, number=10000))
# 1.878 seconds
print(timeit('sorted(l, key=lambda _: random.random())', setup=setup, number=10000))
sorted(l, key=lambda _: random.random())
不是对数组进行洗牌的正确方法:请参见上述链接。 - Sebastian Simonrandom.shuffle
使用的是Fisher-Yates算法(假设我正确地阅读了维基百科和源代码)。该链接提到,如果排序算法本身随机打破平局(Python不会;它是稳定排序),那么使用sorted
与random.random()
将是正确的。 - ShadowRanger