您需要一个pairwise()(或grouped())实现。
def pairwise(iterable):
"s -> (s0, s1), (s2, s3), (s4, s5), ..."
a = iter(iterable)
return zip(a, a)
for x, y in pairwise(l):
print("%d + %d = %d" % (x, y, x + y))
或者,更一般地说:
def grouped(iterable, n):
"s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
return zip(*[iter(iterable)]*n)
for x, y in grouped(l, 2):
print("%d + %d = %d" % (x, y, x + y))
在 Python 2 中,您应该导入 izip 来替代 Python 3 的内置 zip() 函数。
martineau his answer 到 my question 的所有功劳,我发现这非常有效,因为它只在列表上迭代一次,并且在此过程中不会创建任何不必要的列表。
注意:这不应与 Python 自己的 itertools documentation 中的 pairwise recipe 混淆,后者产生 s -> (s0, s1), (s1, s2), (s2, s3), ...,正如 cmets 中的 @lazyr 所指出的那样。
对于那些希望在 Python 3 上使用 mypy 进行类型检查的人来说,这是一个小小的补充:
from typing import Iterable, Tuple, TypeVar
T = TypeVar("T")
def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]:
"""s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ..."""
return zip(*[iter(iterable)] * n)