考虑这种情况:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
walk = os.walk('/home')
for root, dirs, files in walk:
for pathname in dirs+files:
print os.path.join(root, pathname)
for root, dirs, files in walk:
for pathname in dirs+files:
print os.path.join(root, pathname)
我知道这个例子有点多余,但您应该考虑我们需要walk多次使用相同的数据.我有一个基准测试场景,必须使用相同的walk数据才能获得有用的结果.
我试图walk2 = walk在第二次迭代中克隆并使用,但它没有用.问题是......我怎么能复制它?它有可能吗?
先感谢您.
最近类似的问题(isinstance(FOO,types.GeneratorType)或inspect.isgenerator(富)? )让我好奇如何一般实现这一点.
这似乎是一个普遍,有用的东西有,实际上,有一台发电机型对象,将通过(如缓存第一次itertools.cycle),报告StopIteration异常,再从缓存下一次通过返回的项目,但如果对象ISN不是生成器(即本质上支持O(1)查找的列表或字典),然后不缓存,并且具有相同的行为,但对于原始列表.
可能性:
1)修改itertools.cycle.它看起来像这样:
def cycle(iterable):
saved = []
try:
saved.append(iterable.next())
yield saved[-1]
isiter = True
except:
saved = iterable
isiter = False
# cycle('ABCD') --> A B C D A B C D A B C D ...
for element in iterable:
yield element
if isiter:
saved.append(element)
# ??? What next?
Run Code Online (Sandbox Code Playgroud)
如果我能重新启动发电机,这将是完美的 - 我可以发回一个StopIteration,然后在接下来的gen.next(),进入返回0,即'ABCD的StopIteration ABCD的StopIteration",但它看起来并不像这实际上可能.
第二个是一旦命中StopIteration,则保存有缓存.但它看起来没有任何方法可以进入内部保存的[]字段.也许是这个版本的?
2)或者我可以直接传入列表:
def cycle(iterable, saved=[]):
saved.clear()
try:
saved.append(iterable.next())
yield saved[-1]
isiter = True
except:
saved = iterable
isiter = False …Run Code Online (Sandbox Code Playgroud)