如何反复遍历列表?

时间:2019-11-01 16:13:37

标签: python loops

我正在尝试编写一个将返回Python月份名称序列的。

例如,如果我输入:

gen = next_month('October')
lst = [next(gen) for i in range(15)]
print (lst)

我应该得到:

['November', 'December', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',  'September', 'October', 'November', 'December', 'January'])

但是我使用以下代码获取索引超出范围错误:

month_names = ['January', 'February', 'March', 'April', 'May', 'June',
                'July', 'August', 'September', 'October', 'November', 'December']

def next_month(name: str) -> str:
    "Return a stream of the following months"
    global month_names
    month_index = month_names.index(name)
    while True:
            yield (month_names[month_index])
            month_index = month_index + 1

只是不确定如何修复它。预先感谢您的指导!

2 个答案:

答案 0 :(得分:1)

itertools具有一个cycle函数,该函数循环一个迭代器:

from itertools import cycle

month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

for month in cycle(month_names):
    print(month)

家庭作业版:

def gen_cycle(l):
    cnt = 0
    while True:
        yield l[cnt]
        cnt = (cnt+1)%len(l)

答案 1 :(得分:0)

可能不太适合做家庭作业,但是几个月不用硬编码就可以使用itertools.countdatetime.datetime

def next_month(name):
    date = datetime.strptime(name, '%B')
    for m in count(date.month):
        date = date.replace(month=1+(m%12))
        yield date.strftime('%B')

gen = next_month('October')
print([next(gen) for i in range(15)])

此打印:

['November', 'December', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January']

这也可以使用while循环来完成,尽管使用count是一种快捷方式