mardi 5 janvier 2021

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. 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). I do the latter with 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. E.g. 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)]



Aucun commentaire:

Enregistrer un commentaire