itertools.repeat VS itertools.cycle

mar*_*eva 3 python python-itertools python-2.7

有什么区别itertools.repeat(n)itertools.cycle(n)?看起来,它们产生相同的输出.在我需要某个元素的无限循环的情况下,使用它会更有效吗?

Jar*_*uen 7

简单地说,itertools.repeat将重复给定的参数,itertools.cycle并将循环给定的参数.不要运行此代码,但例如:

from itertools import repeat, cycle

for i in repeat('abcd'): print(i)
# abcd, abcd, abcd, abcd, ...

for i in cycle('abcd'): print(i)
# a, b, c, d, a, b, c, d, ...
Run Code Online (Sandbox Code Playgroud)


Ray*_*ger 5

这些是等价的,但第一个更清晰,更快一点:

it = repeat(x)
it = cycle([x])
Run Code Online (Sandbox Code Playgroud)

但是,循环可以选择重复整个序列:

it = cycle(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])
Run Code Online (Sandbox Code Playgroud)

并且repeat可以选择设置重复次数限制:

it = repeat(x, 5)         # Return five repetitions of x
Run Code Online (Sandbox Code Playgroud)

此外,预期的用例也不同.

特别是,repeat旨在为映射函数提供重复参数:

it = imap(pow, repeat(2), range(10))
Run Code Online (Sandbox Code Playgroud)

虽然周期是用于循环重复的行为.这是一个返回的Python 3示例1/1 - 1/3 + 1/5 - 1/7 + 1/9 + ...:

it = accumulate(map(operator.truediv, cycle([1, -1]), count(1, 2)))
Run Code Online (Sandbox Code Playgroud)

后一个例子展示了所有部件如何组合在一起创建一个"迭代器代数".

希望你发现这很有启发性:-)