dimanche 9 juin 2019

Random from an iterator

I have a list and an iterator that contain the same data. I have the list so that I can return the random element using random.choice. I have made an iterator from the list using the itertools.cycle(listname) method so that I can have round-robin type of accessing elements.

How can I combine both the functions where I should be able access the list of elements randomly and also get round-robin kind of the access keeping only one copy of instead of data instead of making it two (list and an iterator)?

Code:

import random
import itertools

list_name = [1,2,3,4,5,6,7]
list_name_iterator = itertools.cycle(list_name)

def return_random():
    return random.choice(list_name)

def return_round_robin():
    return next(list_name_iterator) 

Or how to apply random.choice() on an iterator?




Aucun commentaire:

Enregistrer un commentaire