选择与随机播放,Python

编程入门 行业动态 更新时间:2024-10-27 08:25:15
本文介绍了选择与随机播放,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

本文发布于:2023-10-28 08:16:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536063.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!