[英]Create a generator to yield random number from a list
I would like to create a generator which spits out a random number from a pre-specified list.我想创建一个生成器,它从预先指定的列表中吐出一个随机数。 Something like this:
像这样的东西:
x = random_select([1,2,3])
next(x) # 1
next(x) # 3
next(x) # 3
next(x) # 2
# and so on
How can I do so?我该怎么做?
Here's my motivation.这是我的动机。 I know I can use
random.choice
to select a value randomly .我知道我可以随机使用
random.choice
来select 一个值。 My issue is that in my program, I sometimes want to randomly select items from a given list, while other times I want to cycle over the elements (a variable number of times for either option).我的问题是,在我的程序中,我有时想从给定列表中随机选择 select 项目,而其他时候我想循环遍历元素(任一选项的次数可变)。 I do the latter with
itertools
:我用
itertools
做后者:
import itertools
y = itertools.cycle([1,2,3])
next(y) # 1
next(y) # 2
next(y) # 3
next(y) # 1
# and so on
I would like to create a generator object which can yield the values of a list randomly instead of in a cycle, so that I can still get out all the values I need with next
and not have to specify when to use random.choice
to retrieve values.我想创建一个生成器 object 可以随机而不是循环生成列表的值,这样我仍然可以得到我需要的所有值
next
而不必指定何时使用random.choice
检索价值观。 Eg currently I do:例如,目前我这样做:
import itertools
import random
l = [1,2,3]
select = 'random'
output = []
cycle = itertools.cycle(l) # could conditionally build this generator
for i in range(10):
if select == 'random':
output.append(random.choice(l))
elif select == 'cycle':
output.append(next(cycle))
I find this logic clunky, and if I add more selection options it might get worse.我发现这个逻辑很笨拙,如果我添加更多选择选项,它可能会变得更糟。 I would like to do something like:
我想做类似的事情:
l = [1,2,3]
select = 'cycle'
options = {'cycle':itertools.cycle, 'random':random_select}
g = options[select](l)
output = [next(g) for i in range(10)]
You can create such a generator like so:您可以像这样创建这样的生成器:
import random
def random_select(l):
while True:
yield random.choice(l)
g = random_select([1,2,3])
This will infinitely yield random choices from l
, and works with the final example above.这将从
l
中无限产生随机选择,并适用于上面的最后一个示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.