我已经阅读了python文档中的示例,但仍然不明白这个方法是什么意思。有人能帮帮我吗?下面是python文档中的两个例子

>>> from collections import defaultdict

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

and

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

参数int和list是干什么用的?


当前回答

文档和解释几乎是不言自明的:

http://docs.python.org/library/collections.html#collections.defaultdict

类型函数(int/str等)作为参数传递,用于初始化dict中没有的任何给定键的默认值。

其他回答

Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int(), which will return the integer object 0. For the second example, default items are created using list(), which returns a new empty list object.

defaultdict意味着如果在字典中没有找到一个键,那么不会抛出KeyError,而是创建一个新条目。这个新条目的类型由defaultdict的参数给出。

例如:

somedict = {}
print(somedict[3]) # KeyError

someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0

文档和解释几乎是不言自明的:

http://docs.python.org/library/collections.html#collections.defaultdict

类型函数(int/str等)作为参数传递,用于初始化dict中没有的任何给定键的默认值。

简而言之:

Defaultdict (int) -参数int表示值将是int类型。

Defaultdict (list) -参数列表指示值将是列表类型。

如果没有defaultdict,您可能可以为不可见的键分配新值,但不能修改它。例如:

import collections
d = collections.defaultdict(int)
for i in range(10):
  d[i] += i
print(d)
# Output: defaultdict(<class 'int'>, {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9})

import collections
d = {}
for i in range(10):
  d[i] += i
print(d)
# Output: Traceback (most recent call last): File "python", line 4, in <module> KeyError: 0