小编maz*_*ore的帖子

为什么 random.shuffle 比使用 sorted 函数慢这么多?

使用 pythonsrandom.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))
Run Code Online (Sandbox Code Playgroud)

python random performance shuffle

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

标签 统计

performance ×1

python ×1

random ×1

shuffle ×1