擅长:python、mysql、java
<p>首先,让我们解决发电机问题。正如您所提到的,您只希望在每个迭代中使用next(test)一次。最简单的解决方案是循环测试,这与调用next完全相同:</p>
<pre><code>word_list = [s for _, s in zip(range(10), test)]
</code></pre>
<p>此代码将从生成器中提取前10个单词。现在,您希望它只接受唯一的值。如果您不介意顺序,您可以将其转换为集合,而不是在列表comp中检查:</p>
<pre><code>word_list = set([s for _, s in zip(range(10), test)])
</code></pre>
<p>如果您不介意顺序,可以使用<a href="https://github.com/ActiveState/code/blob/3b27230f418b714bc9a0f897cb8ea189c3515e99/recipes/Python/576696_OrderedSet_with_Weakrefs/recipe-576696.py" rel="nofollow noreferrer">OrderSet recipe</a>,或者更简单地使用OrderedDict:</p>
<pre><code>from collections import OrderedDict
word_list = [t[0] for t in OrderedDict({s:_ for _, s in zip(range(10), test)})]
</code></pre>
<p>最终会得到与for循环相同的输出。
这个解决方案不太好读,我必须说我更喜欢使用旧的nice for循环。你知道吗</p>
<p>或者更像@tobias\u k建议的那样:</p>
<pre><code>from collections import OrderedDict
from itertools import islice
word_list = list(OrderedDict({s:s for s in islice(test, 0, 10)}))
</code></pre>