迭代列表中的每两个元素 [英] Iterating over every two elements in a list
问题描述
如何制作 for
循环或列表推导式,以便每次迭代都给我两个元素?
How do I make a for
loop or a list comprehension so that every iteration gives me two elements?
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()
代码>) 实现.
You need a pairwise()
(or grouped()
) implementation.
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()
函数.
In Python 2, you should import izip
as a replacement for Python 3's built-in zip()
function.
martineau-a-python-dictionary-from-a-line-of-text/4356415#4356415">他对我的回答问题,我发现这非常有效,因为它只在列表上迭代一次,并且不会在此过程中创建任何不必要的列表.
All credit to martineau for his answer to my question, I have found this to be very efficient as it only iterates once over the list and does not create any unnecessary lists in the process.
注意:这不应与 pairwise
recipe 在 Python 自己的 itertools
文档,产生 s ->(s0, s1), (s1, s2), (s2, s3), ...
,正如 所指出的@lazyr 在评论中.
N.B: This should not be confused with the pairwise
recipe in Python's own itertools
documentation, which yields s -> (s0, s1), (s1, s2), (s2, s3), ...
, as pointed out by @lazyr in the comments.
对于那些想在 Python 3 上使用 mypy 进行类型检查的人来说,补充一点:
Little addition for those who would like to do type checking with mypy on Python 3:
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)
这篇关于迭代列表中的每两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!