Python infinite generator for days of the week

I saw similar questions, my little more practical, I would like to repeat a few week days again and again.

Until my iterator is looping, help me solve this.

def day_generator():
    for w in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']:
        yield w;

g = day_generator()
print g.next() 
+4
source share
3 answers

You can use the itertool loop: https://docs.python.org/2/library/itertools.html#itertools.cycle

import itertools
def day_generator():
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    for day in itertools.cycle(days):
        yield day

In short (and as mentioned in the comments), it’s enough to do:

day_generator = itertools.cycle(days)

Thanks @FlavianHautbois

+6
source

This was almost the case with you, you just had to put the yield statement in an infinite loop so that it always wraps around when it was needed:

def day_generator():
    while True:
        for w in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']:
            yield w

g = day_generator()
for _ in range(10):
    print(next(g))

##Output:
##
##    Monday
##    Tuesday
##    Wednesday
##    Thursday
##    Friday
##    Saturday
##    Sunday
##    Monday
##    Tuesday
##    Wednesday

, , itertools.cycle .

0

itertools.cycle , :

import itertools

day_generator = itertools.cycle(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])
-1

All Articles