相关疑难解决方法(0)

如何克隆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数据才能获得有用的结果.

我试图walk2 = walk在第二次迭代中克隆并使用,但它没有用.问题是......我怎么能复制它?它有可能吗?

先感谢您.

python clone generator object

52
推荐指数
4
解决办法
2万
查看次数

使用itertools.tee复制嵌套迭代器(即itertools.groupby)

我正在读一个文件(在做一些昂贵的逻辑时),我需要在不同的函数中迭代几次,所以我真的只想读取和解析文件一次.

解析函数解析文件并返回一个itertools.groupby对象.

def parse_file():
    ...
    return itertools.groupby(lines, key=keyfunc)
Run Code Online (Sandbox Code Playgroud)

我考虑过做以下事情:

csv_file_content = read_csv_file()

file_content_1, file_content_2 = itertools.tee(csv_file_content, 2)

foo(file_content_1)
bar(file_content_2)
Run Code Online (Sandbox Code Playgroud)

但是,itertools.tee似乎只能"复制"外部迭代器,而内部(嵌套)迭代器仍然引用原始(因此在迭代返回的第一个迭代器后它将耗尽itertools.tee).

独立MCVE:

from itertools import groupby, tee

li = [{'name': 'a', 'id': 1},
      {'name': 'a', 'id': 2},
      {'name': 'b', 'id': 3},
      {'name': 'b', 'id': 4},
      {'name': 'c', 'id': 5},
      {'name': 'c', 'id': 6}]

groupby_obj = groupby(li, key=lambda x:x['name'])
tee_obj1, tee_obj2 = tee(groupby_obj, 2)

print(id(tee_obj1))
for group, data in tee_obj1:
    print(group)
    print(id(data))
    for i …
Run Code Online (Sandbox Code Playgroud)

python iterator python-itertools

7
推荐指数
1
解决办法
114
查看次数

标签 统计

python ×2

clone ×1

generator ×1

iterator ×1

object ×1

python-itertools ×1