Skip to main content
 首页 » 编程设计

python之使用生成器循环遍历列表中的数字

2025年05月04日14lovecherry

我正在寻找一种在每次调用函数时循环访问列表中的数字的方法。

我使用了一个生成器,它一次返回一个列表的成员,但我还没有找到在函数返回最后一个元素后返回到列表开头的方法。

def returnSeq(self, numRows): 
    for seq in [0, 1, 2, 3, 2, 1]: 
        yield seq 

如果有更好的方法来实现这一点,我将不胜感激。

提前谢谢你,

请您参考如下方法:

你基本上是在重新实现 itertools.cycle :

import itertools 
 
itertools.cycle([0, 1, 2, 3, 2, 1]) # <- there's your infinite generator