Python random.choice()函数-如何永远不会连续出现两个选择或彼此接近 [英] Python random.choice() function - how to never have two choices in a row or close to one another
问题描述
假设我有
mychoice = random.choice(['this is random response 1','this is random response 2',
'this is random response 3', 'and 4', 'and so on'])
如何避免同一选择连续重复多次?或者,我如何设置条件以使某个特定选择仅在选择了某些其他选择之后才会出现?还是在这方面有一个更适合我需要的模块?
How can I avoid having the same choice being repeated more than once in a row? Or how can I can I set a condition to make a particular choice only appear after a certain number of other choices have been chosen? Or is there a module better suited to my needs in this regard?
推荐答案
最简单的解决方案可能是构造一个长度为k
的usedQueue
(其中k是允许重复选择的选择数. )选择一个选项后,将其从原始列表中删除并将其放置在usedQueue
中.然后,如果usedQueue.length > k
,则将其弹出回到您的阵列中.
the simplest solution would probably be to construct a usedQueue
of length k
(where k is the number of selections before a choice is allowed to repeat.) When you select a choice, remove it from your original list and place it in usedQueue
. Then, if usedQueue.length > k
, pop one back onto your array.
如前所述,这大大降低了算法的随机性.也就是说,它确实有实际用途(请查看iTunes.)
As already stated, this significantly reduces the randomness of your algorithm. That said, it does have practical uses (take a look at iTunes.)
这篇关于Python random.choice()函数-如何永远不会连续出现两个选择或彼此接近的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!