擅长:python、mysql、java
<p>实现新类型迭代的最佳方法是编写生成器。它们允许您封装迭代样式并将其与其他代码分开:</p>
<pre><code>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
</code></pre>
<p>印刷品:</p>
^{pr2}$
<p>如果需要灵活地对序列进行元组化,可以使用以下命令:</p>
<pre><code>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 = []
</code></pre>