<p>你可以用<a href="https://docs.python.org/library/collections.html#collections.Counter" rel="nofollow noreferrer">^{<cd1>}</a>来理解:</p>
<pre><code>from collections import Counter
Counter(str(i) for i in s)
</code></pre>
<p><code>Counter</code>在这里工作,因为您的增量是1。但是,如果您希望它更通用,也可以使用<a href="https://docs.python.org/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">^{<cd3>}</a>:</p>
<pre><code>from collections import defaultdict
dd = defaultdict(int) # use int as factory - this will generate 0s for missing entries
for i in s:
dd[str(i)] += 1 # but you could also use += 2 or whatever here.
</code></pre>
<p>或者,如果希望将其作为普通字典,请将其包装在<code>dict</code>调用中,例如:</p>
<pre><code>dict(Counter(str(i) for i in s))
</code></pre>
<p>这两种方法都避免了键还没有出现时的<code>KeyError</code>,并且避免了双循环。你知道吗</p>
<hr/>
<p>另请注意:如果您想要普通的dict,也可以使用<a href="https://docs.python.org/library/stdtypes.html#dict.get" rel="nofollow noreferrer">^{<cd6>}</a>:</p>
<pre><code>d = {} # empty dict
for i in d:
d[str(i)] = d.get(str(i), 0) + 1
</code></pre>
<p>但是<code>Counter</code>和<code>defaultdict</code>的行为几乎像普通字典,所以几乎不需要最后一个,因为它(可能)比较慢,而且在我看来可读性较差。你知道吗</p>