擅长:python、mysql、java
<p>(Python的itertools应该真正将<a href="http://docs.python.org/library/itertools.html#itertools-recipes" rel="nofollow noreferrer">all recipes</a>作为标准函数…)</p>
<p>您可以使用<code>grouper</code>函数:</p>
<pre><code>from itertools import zip_longest
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
</code></pre>
<p>然后你可以通过</p>
<pre><code>for r,g,b,a in grouper(4, raw_png_data):
....
</code></pre>
<p>或者,你可以使用</p>
<pre><code>irpd = iter(raw_png_data)
for r,g,b,a in zip(irpd, irpd, irpd, irpd): # use itertools.izip in Python 2.x
....
</code></pre>
<p>注意,如果iterable的长度不是4的倍数,则这将截断最后几个字节。噢,<code>grouper</code>函数使用<code>izip_longest</code>,因此额外的字节将填充为没有。</p>