代码之家  ›  专栏  ›  技术社区  ›  moshevi

使用不同的迭代器继续迭代器而不影响第一个迭代器[重复]

  •  0
  • moshevi  · 技术社区  · 8 年前

    iter 函数并使用迭代器迭代几个步骤。

    考虑迭代器对象 org_iter :

    >>> a = [1,2,3,4,5]
    >>> org_iter = iter(a)
    

    在上面迭代:

    >>> next(org_iter)
    1
    

    使用 iter 再次给出迭代器的相同实例,而不是来自同一位置的不同实例:

    >>> new_iter = iter(org_iter)
    >>> next(new_iter)  # continuing 
    2
    >>> next(org_iter)  # "org_iter is new_iter"
    3
    

    itertools.tee 也不起作用:

    >>> new_iter = itertools.tee(org_iter)
    >>> next(new_iter[0])
    2
    >>> next(org_iter)
    3
    

    +=1

    或者和 enumerate 函数和嵌套 for

    1 回复  |  直到 8 年前
        1
  •  1
  •   BPL    8 年前

    不使用任何外部模块的一种方法是:

    >>> a = [1, 2, 3, 4, 5]
    >>> org_iter = iter(a)
    >>> id(org_iter)
    58713584
    >>> new_iter = iter(list(org_iter))
    >>> id(new_iter)
    58299600