简体   繁体   中英

Infinite generator in Python for days of week

I have seen similar questions, my is little bit more practical, I would like to iterate over range of week days over and over again.

So far my iterator is not cyclic, help me please to resolve this.

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

g = day_generator()
print g.next() 

You can use itertool's cycle: 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

Long story short(and as mentioned in comments) it is really enough to make:

day_generator = itertools.cycle(days)

Thanks @FlavianHautbois

You almost had it, you just needed to put your "yield" statement in an endless loop, so that it will always wrap around when 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

However, as others have noted, itertools.cycle is the most concise way to do it.

itertools.cycle does exactly what you want:

import itertools

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM