这是来自itertools 模块文档的相关示例:
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
对于 Python 2,您需要 itertools.izip 而不是 zip:
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
这是如何工作的:
首先,创建两个并行迭代器a 和b(tee() 调用),它们都指向原始可迭代对象的第一个元素。第二个迭代器 b 向前移动了 1 步(next(b, None))调用)。此时a指向s0,b指向s1。 a 和 b 都可以独立地遍历原始迭代器 - izip 函数采用两个迭代器并将返回的元素配对,以相同的速度推进两个迭代器。
一个警告:tee() 函数产生两个迭代器,它们可以相互独立地前进,但这是有代价的。如果其中一个迭代器比另一个更进一步,则tee() 需要将消耗的元素保留在内存中,直到第二个迭代器也使用它们(它不能“倒回”原始迭代器)。这里没关系,因为一个迭代器只领先另一个迭代器 1 步,但通常这种方式很容易使用大量内存。
由于tee() 可以接受n 参数,这也可以用于两个以上的并行迭代器:
def threes(iterator):
"s -> (s0,s1,s2), (s1,s2,s3), (s2, s3,4), ..."
a, b, c = itertools.tee(iterator, 3)
next(b, None)
next(c, None)
next(c, None)
return zip(a, b, c)