<p>在Python3.4和更高版本中,可以使用新函数<a href="https://docs.python.org/3/library/struct.html#struct.iter_unpack" rel="nofollow noreferrer">^{<cd1>}</a>。在</p>
<blockquote>
<p><code>struct.iter_unpack(fmt, buffer)</code></p>
<p>Iteratively unpack from the buffer buffer according to the format string fmt. This function returns an iterator which will read equally-sized chunks from the buffer until all its contents have been consumed. The buffer’s size in bytes must be a multiple of the size required by the format, as reflected by calcsize().<br/><br/>
Each iteration yields a tuple as specified by the format string.</p>
</blockquote>
<p>假设我们要用重复格式字符串<code>'<2sc'</code>(2个字符后跟一个字符,重复直到完成)来解压数组{<cd2>}。在</p>
<p>使用<code>iter_unpack</code>,可以执行以下操作:</p>
<pre><code>>>> import struct
>>> some_bytes = b'\x01\x02\x03'*3
>>> fmt = '<2sc'
>>>
>>> tuple(struct.iter_unpack(fmt, some_bytes))
((b'\x01\x02', b'\x03'), (b'\x01\x02', b'\x03'), (b'\x01\x02', b'\x03'))
</code></pre>
<p>如果要取消嵌套此结果,可以使用<a href="https://docs.python.org/3.5/library/itertools.html#itertools.chain.from_iterable" rel="nofollow noreferrer">^{<cd5>}</a>执行此操作。在</p>
^{pr2}$
<p>当然,您可以使用嵌套的理解来做同样的事情。在</p>
<pre><code>>>> tuple(x for subtuple in struct.iter_unpack(fmt, some_bytes) for x in subtuple)
(b'\x01\x02', b'\x03', b'\x01\x02', b'\x03', b'\x01\x02', b'\x03')
</code></pre>