<p>让我们将<code>addToInventory</code>函数中的循环分解。首先我们有</p>
<pre class="lang-python prettyprint-override"><code>inventory.setdefault(i ,0)
</code></pre>
<p>此指令表示“如果<code>i</code>键不在<code>inventory</code>字典中,请将其设置为<code>0</code>。在本例中(因为我们不使用<a href="https://docs.python.org/3/library/stdtypes.html#dict.setdefault" rel="nofollow noreferrer">^{<cd5>}</a>的返回值),它相当于</p>
<pre class="lang-python prettyprint-override"><code>if i not in inventory.keys():
inventory[i] = 0
</code></pre>
<p>接下来是这个指令</p>
<pre class="lang-python prettyprint-override"><code>inventory[i] = inventory[i] + 1
</code></pre>
<p>它基本上是一个<a href="https://en.wikipedia.org/wiki/Increment_and_decrement_operators" rel="nofollow noreferrer">incrementation</a>,<em>,也就是说,</em>为<code>i</code>键的<code>inventory</code>值加1</p>
<p>另一种解释是,<code>for</code>循环是“对于<code>addedItems</code>中的每一项,将<code>inventory</code>字典中的对应值设置为零(如果尚未存在),然后将其递增”</p>
<hr/>
<p>读完本书后,您可能会从花一些时间检查Python标准库的<a href="https://docs.python.org/3.8/library/collections.html" rel="nofollow noreferrer">^{<cd11>}</a>模块中获益,尤其是<a href="https://docs.python.org/3.8/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">^{<cd12>}</a>和<a href="https://docs.python.org/3.8/library/collections.html#collections.Counter" rel="nofollow noreferrer">^{<cd13>}</a>模块,它们更适合您尝试实现的逻辑</p>