Python-迭代一次迭代器两次 [英] Python -- Iterate an iterator twice

查看:74
本文介绍了Python-迭代一次迭代器两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处有一个类似的问题,涉及迭代器重置.但是,下面接受的答案解决了嵌套迭代器的实际问题,并处理了一个容易遗漏的问题,即嵌套迭代器不会重置.

There is a similar question here that deals with iterator resetting. The accepted answer below however addresses the actual issue of nested iterators, and handles an easy to miss issue, whereby the nested iterator doesn't reset.

有什么办法可以在python中迭代两次迭代器吗?

Is there any way to iterate over an iterator twice in python?

在下面的示例代码中,我可以看到第二个迭代与第一个迭代在同一个对象上进行操作,因此产生了一个奇怪的结果.将此与下面的C#进行对比,得出我想要的结果.

In the example code below I can see that the second iteration is operating on the same object as the first, and thus yields a weird result. Contrast this with the C# below that yields the result I'm after.

有什么办法可以做我想做的事.我想知道是否可以复制迭代器或检索"其来源的功能,但是也许有一种更简单的方法.(我知道我可以在下面的玩具示例中两次调用 MyIter(),但是如果我不知道迭代器的来源并且不是我想要的,那将毫无用处!).

Is there any way to do what I want. I was wondering if I could make a copy of the iterator or "retrieve" the function it came from, but maybe there's a simpler way. (I know I could just call MyIter() twice in the toy example below, but that's useless if I don't know where the iterator came from and isn't what I'm after!).

def MyIter():
  yield 1;
  yield 2;
  yield 3;
  yield 4;

def PrintCombos(x):
  for a in x:
      for b in x:
          print(a,"-",b);

PrintCombos(MyIter());

给予

1 - 2
1 - 3
1 - 4

对比:

static IEnumerable MyIter()
{
    yield return 1;
    yield return 2;
    yield return 3;
    yield return 4;
}

static void PrintCombos(IEnumerable x)
{
    foreach (var a in x)
        foreach (var b in x)
            Console.WriteLine(a + "-" + b);
}

public static void Main(String[] args)
{
    PrintCombos(MyIter());
}

哪个给:

1-1
1-2
1-3
1-4
2-1
2-2
. . .

推荐答案

您可以使用 itertools.tee 创建生成器的多个副本

You could use itertools.tee to create multiple copies of the generator

from itertools import tee

def MyIter():
    yield 1
    yield 2
    yield 3
    yield 4

def PrintCombos(x):
    it1, it2 = tee(x, 2)
    for a in it1:
        it2, it3 = tee(it2, 2)
        for b in it3:
        print("{0}-{1}".format(a, b))

PrintCombos(MyIter())

这篇关于Python-迭代一次迭代器两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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