def by_threes(seq):
it = iter(seq)
while True:
yield next(it), next(it), next(it)
for a, b, c in by_threes(range(20)):
print a,b,c
印刷品:
^{pr2}$
如果需要灵活地对序列进行元组化,可以使用以下命令:
def by_chunks(seq, n):
"""Yield lists [a,b,..] from `seq`, each list having `n` elements."""
l = []
for i, x in enumerate(seq):
l.append(x)
if (i % n) == n-1:
yield l
l = []
from itertools import izip
iters = [iter(my_list)] * 3 # change 3 to number of items in each group
for name, age, nationality in izip(*iters):
print name, age, nationality
实现新类型迭代的最佳方法是编写生成器。它们允许您封装迭代样式并将其与其他代码分开:
印刷品:
^{pr2}$如果需要灵活地对序列进行元组化,可以使用以下命令:
试试这个方便的模式:
将步骤索引与^{} (或^{} )一起使用:
相关问题 更多 >
编程相关推荐