<p>函数<code>groupby</code>和<code>takewhile</code>不适合这类问题。在</p>
<h2><code>groupby</code></h2>
<p>基于<code>key</code>函数的<a href="https://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">^{<cd1>}</a>组。这意味着您需要保留最后遇到的第一个非空白元组元素才能使其正常工作。这意味着你要保持一些全球性的状态。通过保持这种状态,函数被称为<a href="https://en.wikipedia.org/wiki/Pure_function" rel="nofollow noreferrer">"unpure"</a>,而大多数(甚至所有)itertools都是纯函数。在</p>
<pre><code>from itertools import groupby, chain
d = [('FRG', 'MCO TPA PIE SRQ', 'WAVEY EMJAY J174 SWL CEBEE '),
(' ', 'FMY RSW APF', 'WETRO DIW AR22 JORAY HILEY4'),
(' ', 'FMY RSW APF', 'WETRO DIW AR22 JORAY HILEY4'),
('FRG2', 'MCO TPA PIE SRQ', 'WAVEY EMJAY J174 SWL CEBEE '),
(' ', 'FMY RSW APF', 'WETRO DIW AR22 JORAY HILEY4')]
def keyfunc(item):
first = item[0]
if first.strip():
keyfunc.state = first
return keyfunc.state
{k: [item for idx, item in enumerate(chain.from_iterable(grp)) if idx%3 != 0] for k, grp in groupby(d, keyfunc)}
</code></pre>
<h2><code>takewhile</code></h2>
<p><a href="https://docs.python.org/library/itertools.html#itertools.takewhile" rel="nofollow noreferrer">^{<cd2>}</a>需要向前看,以确定何时停止<code>yield</code>值。这意味着它将自动从迭代器中弹出一个值,而不是实际用于每个组的值。要实际应用它,您需要记住最后一个位置,然后每次创建一个新的迭代器。它也有一个问题,你需要保持某种状态,因为你想取一个不带空格的元素,然后是那些只有空格的第一个元素。在</p>
<p>一种方法可能看起来像这样(但感觉不必要地复杂):</p>
^{pr2}$
<h2>替代方案</h2>
<p>您可以简单地创建自己的生成器,使之非常简单。它是<code>takewhile</code>方法的变体,但它不需要外部状态、<code>islice</code>、<code>takewhile</code>、<code>groupby</code>或跟踪索引:</p>
^{3}$