循环遍历迭代器中的元素
cycle
是一个无限的迭代器。
>>> import itertools as it
>>> it.cycle('ABCD')
A B C D A B C D A B C D ...
因此,在使用它时要注意给出边界以避免无限循环。例:
>>> # Iterate over each element in cycle for a fixed range
>>> cycle_iterator = it.cycle('abc123')
>>> [next(cycle_iterator) for i in range(0, 10)]
['a', 'b', 'c', '1', '2', '3', 'a', 'b', 'c', '1']