【发布时间】:2021-04-11 17:29:17
【问题描述】:
我想创建一个生成器,它从预先指定的列表中生成一个随机数。像这样的:
x = random_select([1,2,3])
next(x) # 1
next(x) # 3
next(x) # 3
next(x) # 2
# and so on
我该怎么做?
这是我的动机。我知道我可以使用random.choice 到select a value randomly。我的问题是,在我的程序中,有时我想从给定列表中随机选择项目,而其他时候我想循环遍历元素(任一选项的次数可变)。我用itertools做后者:
import itertools
y = itertools.cycle([1,2,3])
next(y) # 1
next(y) # 2
next(y) # 3
next(y) # 1
# and so on
我想创建一个生成器对象,它可以随机而不是循环生成列表的值,这样我仍然可以使用next 获取我需要的所有值,而不必指定何时使用random.choice 检索值。例如。目前我这样做:
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))
我发现这个逻辑很笨拙,如果我添加更多选择选项,它可能会变得更糟。我想做类似的事情:
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)]
【问题讨论】: