python - 一周中几天的 Python 无限生成器

标签 python generator

我见过类似的问题,我的更实际一点,我想一遍又一遍地遍历工作日的范围。

到目前为止我的迭代器不是循环的,请帮我解决这个问题。

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

g = day_generator()
print g.next() 

最佳答案

可以使用itertool的循环: 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

长话短说(正如评论中提到的)它真的足够了:

day_generator = itertools.cycle(days)

感谢@FlavianHautbois

关于python - 一周中几天的 Python 无限生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626995/

相关文章:

python - 如何找到最低位置的白色像素?

python - 使用 Pyramid 在 View 和应用程序之间共享对象

python - 模糊的 Pygame 矩形错误

python - 在 PyQt5 中显示和隐藏多个窗口

haskell - 在 Haskell 中生成不等于指定整数的整数列表?

python - 在Python中将生成器中的元组存储在字典中

python - 在 MacOSX 10.7.5 上安装 lxml 时出错 :

javascript - 将多次调用的回调转换为生成器函数

python - Redis 与 Disk 在缓存应用程序中的性能

javascript - Promise.all 对遍历生成器无效