如何制作 for
循环或列表推导式,以便每次迭代都给我两个元素?
l = [1,2,3,4,5,6]
for i,k in ???:
print str(i), '+', str(k), '=', str(i+k)
输出:
1+2=3
3+4=7
5+6=11
最佳答案
您需要一个 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 ,我发现这非常有效,因为它只在列表上迭代一次,并且不会在此过程中创建任何不必要的列表。
注意:这不应与 pairwise
recipe 混淆。在 Python 自己的 itertools
documentation ,产生 s -> (s0, s1), (s1, s2), (s2, s3), ...
,正如 @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)
https://stackoverflow.com/questions/5389507/