Python itertools.repeat VS itertools.cycle
Python itertools.repeat VS itertools.cycle,python,python-2.7,itertools,Python,Python 2.7,Itertools,itertools.repeat(n)和itertools.cycle(n)之间有什么区别吗?看起来,它们的产量是一样的。在我需要某个元素的无限循环的情况下使用一个更有效吗?简单地说,itertools.repeat将重复给定的参数,itertools.cycle将循环给定的参数。不要运行此代码,例如: from itertools import repeat, cycle for i in repeat('abcd'): print(i) # abcd, abcd, abcd, abcd,
itertools.repeat(n)
和itertools.cycle(n)
之间有什么区别吗?看起来,它们的产量是一样的。在我需要某个元素的无限循环的情况下使用一个更有效吗?简单地说,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, ...
这些是等效的,但第一个更清晰,速度更快:
it = repeat(x)
it = cycle([x])
但是,cycle可以选择重复整个序列:
it = cycle(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])
“重复”可以选择设置重复次数的限制:
it = repeat(x, 5) # Return five repetitions of x
此外,预期的用例也不同
特别是,repeat旨在为映射函数提供重复参数:
it = imap(pow, repeat(2), range(10))
而循环则用于循环重复性行为。下面是一个Python 3示例,它返回1/1-1/3+1/5-1/7+1/9+…
:
it = accumulate(map(operator.truediv, cycle([1, -1]), count(1, 2)))
后一个示例显示了如何将所有部分组合在一起创建“迭代器代数”
希望您发现这一点很有启发性:-)itertools.cycle()
使用迭代器。例如,您不能执行itertools.cycle(5)
-这将抛出一个错误:
>>> itertools.cycle(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
执行itertools.cycle([1,2,3])
返回一个无限列表,看起来像[1,2,3,1,2,2,3,…]
(或者至少如果您能将其放入内存中)
差别相当大
itertools.repeat
反复返回同一对象,而itertools.cycle
反复迭代同一对象。因此:
import itertools
# Warning: infinite loop ahead
for x in itertools.repeat([1, 2, 3]):
print(x)
# [1, 2, 3], [1, 2, 3], ...
for x in itertools.cycle([1, 2, 3]):
print(x)
# 1, 2, 3, 1, 2, 3, ...
因此,如果您想要的是多次返回一个对象的内容,请使用
itertools。重复;如果是在不同对象上循环的内容,请使用itertools.cycle
参考itertools文档了解差异
>>> import itertools
>>> help(itertools.repeat)
Help on class repeat in module itertools:
class repeat(__builtin__.object)
| repeat(object [,times]) -> create an iterator which returns the object
| for the specified number of times. If not specified, returns the object
| endlessly.
|
...
...
>>> help(itertools.cycle)
Help on class cycle in module itertools:
class cycle(__builtin__.object)
| cycle(iterable) --> cycle object
|
| Return elements from the iterable until it is exhausted.
| Then repeat the sequence indefinitely.
|
如果您也使用“abcd”作为重复函数的参数,则该示例会更好。如果您只需要元素的无限序列,请使用repeat
,下面的答案将解释这些差异。@JaredGoguen I concur。重复版本更清晰、更快。这是首选方法。
>>> import itertools
>>> help(itertools.repeat)
Help on class repeat in module itertools:
class repeat(__builtin__.object)
| repeat(object [,times]) -> create an iterator which returns the object
| for the specified number of times. If not specified, returns the object
| endlessly.
|
...
...
>>> help(itertools.cycle)
Help on class cycle in module itertools:
class cycle(__builtin__.object)
| cycle(iterable) --> cycle object
|
| Return elements from the iterable until it is exhausted.
| Then repeat the sequence indefinitely.
|