我如何创建一个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
我如何创建一个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
当前回答
使用类型,以便您可以使用myypy静态分析工具验证数据:
from typing import Iterator, Any, Iterable, TypeVar, Tuple
T_ = TypeVar('T_')
Pairs_Iter = Iterator[Tuple[T_, T_]]
def legs(iterable: Iterator[T_]) -> Pairs_Iter:
begin = next(iterable)
for end in iterable:
yield begin, end
begin = end
其他回答
您需要一个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对我问题的回答,我发现这是非常有效的,因为它只在列表上迭代一次,并且不会在这个过程中创建任何不必要的列表。
注意:不要将其与Python自己的itertools文档中的成对recipe混淆,后者生成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)
简单的方法:
[(a[i],a[i+1]) for i in range(0,len(a),2)]
如果你的数组是a,并且你想成对迭代它,这是很有用的。 要迭代三胞胎或更多,只需更改"range" step命令,例如:
[(a[i],a[i+1],a[i+2]) for i in range(0,len(a),3)]
(如果你的数组长度和步长不匹配,你必须处理多余的值)
这里我们有alt_elem方法,它可以放入for循环中。
def alt_elem(list, index=2):
for i, elem in enumerate(list, start=1):
if not i % index:
yield tuple(list[i-index:i])
a = range(10)
for index in [2, 3, 4]:
print("With index: {0}".format(index))
for i in alt_elem(a, index):
print(i)
输出:
With index: 2
(0, 1)
(2, 3)
(4, 5)
(6, 7)
(8, 9)
With index: 3
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
With index: 4
(0, 1, 2, 3)
(4, 5, 6, 7)
注意:考虑到在func中执行的操作,上述解决方案可能不是有效的。
>>> l = [1,2,3,4,5,6]
>>> zip(l,l[1:])
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
>>> zip(l,l[1:])[::2]
[(1, 2), (3, 4), (5, 6)]
>>> [a+b for a,b in zip(l,l[1:])[::2]]
[3, 7, 11]
>>> ["%d + %d = %d" % (a,b,a+b) for a,b in zip(l,l[1:])[::2]]
['1 + 2 = 3', '3 + 4 = 7', '5 + 6 = 11']
我需要把一个列表除以一个数字,然后像这样固定。
l = [1,2,3,4,5,6]
def divideByN(data, n):
return [data[i*n : (i+1)*n] for i in range(len(data)//n)]
>>> print(divideByN(l,2))
[[1, 2], [3, 4], [5, 6]]
>>> print(divideByN(l,3))
[[1, 2, 3], [4, 5, 6]]