擅长:python、mysql、java
<p>我想我明白这里发生了什么。你知道吗</p>
<pre><code>def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
</code></pre>
<p>我们还有<code>L = [1, [[2]]]</code>,我们称之为<code>flatten(L)</code>。你知道吗</p>
<p>现在第一个元素是1,现在我们移动到<code>for element in flatten(1)</code>。你知道吗</p>
<p>当我们调用flatten()并遇到TypeError时,我们将得到<code>nested</code>变量,在这里,它是1。你知道吗</p>
<p>所以我们得到了<code>1</code>。你知道吗</p>
<p>原来的L现在只剩下<code>[[2]]</code>。你知道吗</p>
<p>正如我们所调用的for循环:<code>for i in flatten(L)</code>,事情将会继续。你知道吗</p>
<p>我们现在将移到<code>for element in flatten([[2]])</code>,是的,我们在它下面有一个<code>yield element</code>,但是我们必须先执行<code>for element in flatten([[2]])</code>,然后看看发生了什么。你知道吗</p>
<p>现在我们将转到<code>for element in flatten([2])</code>,直接转到它下面的<code>yield element</code>是一种诱惑。但等一下,我们换个时间再谈。你知道吗</p>
<p>现在我们移动到<code>flatten(2)</code>,它将像flatten(1)一样引发TypeError。你知道吗</p>
<p>所以这次我们得到了<code>2</code>。你知道吗</p>
<p>事情解释清楚了!你知道吗</p>