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

查看:129
本文介绍了如何克隆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.

ve尝试 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天全站免登陆