擅长:python、mysql、java
<p>不同之处在于,如果尚未设置键,<code>defaultdict</code>将“默认”一个值。如果不使用<code>defaultdict</code>,则必须检查该键是否存在,如果不存在,则将其设置为所需的值。</p>
<p>lambda正在为默认值定义工厂。该函数在需要默认值时被调用。你可以假设有一个更复杂的默认函数。</p>
<pre><code>Help on class defaultdict in module collections:
class defaultdict(__builtin__.dict)
| defaultdict(default_factory) --> dict with default factory
|
| The default factory is called without arguments to produce
| a new value when a key is not present, in __getitem__ only.
| A defaultdict compares equal to a dict with the same items.
|
</code></pre>
<p>(来自<code>help(type(collections.defaultdict()))</code>)</p>
<p><code>{}.setdefault</code>在本质上是相似的,但是接受一个值而不是一个工厂函数。它用于设置值,如果它不存在。。。不过,这有点不同。</p>