如何克隆 Python 生成器对象? [英] How to clone a Python generator object?

查看:33
本文介绍了如何克隆 Python 生成器对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这种情况:

#!/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 数据才能获得有用的结果.

I know that this example is kinda redundant, but you should consider that we need to use the same walk data more than once. I've a benchmark scenario and the use of same walk data is mandatory to get helpful results.

我试过 walk2 = walk 在第二次迭代中进行克隆和使用,但没有成功.问题是……我怎样才能复制它?有可能吗?

I've tried walk2 = walk to clone and use in the second iteration, but it didn't work. The question is... How can I copy it? Is it ever possible?

提前致谢.

推荐答案

您可以使用 itertools.tee():

You can use itertools.tee():

walk, walk2 = itertools.tee(walk)

请注意,正如文档指出的那样,这可能需要大量额外的存储空间".

Note that this might "need significant extra storage", as the documentation points out.

这篇关于如何克隆 Python 生成器对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆