使用列表我可以这样做:
lst = [1, 2, 3, 4]
assert len(lst) % 2 == 0 # I know that source has n % 2 == 0 elements
for i in range(0, len(lst), 2):
print lst[i] + lst[i+1]
如果lst
是生成器,我怎样才能实现相同的行为?据我所知,这可能需要长度"没有消耗它的发电机。
现在我完成了以下代码:
for l in gen:
r = next(gen)
print l + r
但它并不适用于n-case
答案 0 :(得分:3)
您可以执行以下操作:
In [103]: def lst():
i = 1
while i <= 10:
yield i
i += 1
In [104]: g = lst()
In [105]: while True:
try:
v1, v2 = next(g), next(g)
print(v1,v2)
except StopIteration:
break
.....:
(1, 2)
(3, 4)
(5, 6)
(7, 8)
(9, 10)
答案 1 :(得分:1)
使用xnx的回复中的lst())函数来创建生成器:
def lst():
i = 1
while i <= 10:
yield i
i += 1
gen = lst()
使用itertools的通用解决方案
from itertools import islice
def slice_generator(gen, number_of_elements = 2):
result = []
while 1:
l = tuple(itertools.islice(gen, number_of_elements))
if not l:
return result
result.append(l)
print l
>>> my_list = slice_generator(gen, 3)
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
(10,)
>>> print my_list
[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10,)]