Python中itertools模块用法详解

2019-10-05 18:57:26刘景俊

tee(iterable [, n]):
从iterable创建n个独立的迭代器,创建的迭代器以n元组的形式返回,n的默认值为2,此函数适用于任何可迭代的对象,但是,为了克隆原始迭代器,生成的项会被缓存,并在所有新创建的迭代器中使用,一定要注意,不要在调用tee()之后使用原始迭代器iterable,否则缓存机制可能无法正确工作。

def tee(iterable, n=2):
  it = iter(iterable)
  deques = [collections.deque() for i in range(n)]
  def gen(mydeque):
    while True:
      if not mydeque:       # when the local deque is empty
        newval = next(it)    # fetch a new value and
        for d in deques:    # load it to all the deques
          d.append(newval)
      yield mydeque.popleft()
  return tuple(gen(d) for d in deques)

#Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, 
the iterable could get advanced without the tee objects being informed.
#This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). 
In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

相信本文所述对大家Python程序设计的学习有一定的借鉴价值。