选择与随机播放,Python [英] Choice vs. Shuffle, Python

查看:54
本文介绍了选择与随机播放,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 shuffle()choice() 哪个更有效.例如,我有一个 N 元素列表 long_list 并且需要列表中的随机项,这样做是否更快:

I was wondering which of shuffle() and choice() was more efficient. For example, I have a N element list long_list and need a random item from the list, is it quicker to do:

shuffle(long_list)
return long_list[0]

return choice(long_list)

推荐答案

random.choice() 总是更快,因为它在恒定时间 O(1) 内进行查找

random.choice() will always be faster as it does lookups in constant time O(1)

random.shuffle() 需要遍历整个序列以执行随机播放,这将是 O(n),然后您的查找时间为 O(1)

random.shuffle() requires iterating over the full sequence to execute the shuffle and this would be O(n), and then your lookup which is constant time O(1)

可在此处阅读源代码

这篇关于选择与随机播放,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆