我已经阅读了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是干什么用的?


当前回答

我自己的2分:你也可以子类defaultdict:

class MyDict(defaultdict):
    def __missing__(self, key):
        value = [None, None]
        self[key] = value
        return value

这在非常复杂的情况下可以派上用场。

其他回答

由于这个问题是关于“它是如何工作的”,一些读者可能想了解更多的具体细节。具体来说,问题中的方法是__missing__(key)方法。参见:https://docs.python.org/2/library/collections.html#defaultdict-objects。

更具体地说,这个答案展示了如何以一种实用的方式使用__missing__(key): https://stackoverflow.com/a/17956989/1593924

为了澄清'callable'的含义,这里有一个交互式会话(来自2.7.6,但也适用于v3):

>>> x = int
>>> x
<type 'int'>
>>> y = int(5)
>>> y
5
>>> z = x(5)
>>> z
5

>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd
defaultdict(<type 'int'>, {})
>>> dd = defaultdict(x)
>>> dd
defaultdict(<type 'int'>, {})
>>> dd['a']
0
>>> dd
defaultdict(<type 'int'>, {'a': 0})

这是defaultdict最典型的用法(除了毫无意义地使用x变量)。你可以使用0作为显式默认值,但不能使用简单的值:

>>> dd2 = defaultdict(0)

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    dd2 = defaultdict(0)
TypeError: first argument must be callable

相反,下面的函数可以工作,因为它传递了一个简单的函数(它动态地创建了一个无参数且总是返回0的无名函数):

>>> dd2 = defaultdict(lambda: 0)
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, {})
>>> dd2['a']
0
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, {'a': 0})
>>> 

并且使用不同的默认值:

>>> dd3 = defaultdict(lambda: 1)
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, {})
>>> dd3['a']
1
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, {'a': 1})
>>> 

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

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

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

字典是一种方便的方式来存储数据,以便以后按名称(键)检索。键必须是唯一的、不可变的对象,通常是字符串。字典中的值可以是任何东西。对于许多应用程序,值是简单类型,如整数和字符串。

It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations. A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key.

defaultdict永远不会引发KeyError。任何不存在的键都将获得默认工厂返回的值。

from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')

ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'

print(ice_cream['Sarah'])
>>>Chunky Monkey

print(ice_cream['Joe'])
>>>Vanilla

下面是另一个关于如何使用defaultdict的例子,我们可以降低复杂性

from collections import defaultdict
# Time complexity O(n^2)
def delete_nth_naive(array, n):
    ans = []
    for num in array:
        if ans.count(num) < n:
            ans.append(num)
    return ans

# Time Complexity O(n), using hash tables.
def delete_nth(array,n):
    result = []
    counts = defaultdict(int)

    for i in array:
        if counts[i] < n:
            result.append(i)
            counts[i] += 1
    return result


x = [1,2,3,1,2,1,2,3]
print(delete_nth(x, n=2))
print(delete_nth_naive(x, n=2))

总之,当您需要字典,并且每个元素的值都应该以默认值开始时,请使用defaultdict。

这里有一个关于defaultdicts的很好的解释:http://ludovf.net/blog/python-collections-defaultdict/

基本上,参数int和list是传递的函数。记住,Python接受函数名作为参数。Int默认返回0,而list在使用括号调用时返回空列表。

在正常的字典中,如果在你的例子中我尝试调用d[a],我会得到一个错误(KeyError),因为只有键m, s, I和p存在,键a还没有初始化。但在defaultdict中,它接受函数名作为参数,当您尝试使用未初始化的键时,它只是调用您传入的函数并将其返回值分配为新键的值。

我认为它最好用来代替switch case语句。想象一下,如果我们有一个switch case语句,如下所示:

option = 1

switch(option) {
    case 1: print '1st option'
    case 2: print '2nd option'
    case 3: print '3rd option'
    default: return 'No such option'
}

python中没有switch case语句。我们可以通过使用defaultdict实现同样的目的。

from collections import defaultdict

def default_value(): return "Default Value"
dd = defaultdict(default_value)

dd[1] = '1st option'
dd[2] = '2nd option'
dd[3] = '3rd option'

print(dd[4])    
print(dd[5])    
print(dd[3])

它打印:

Default Value
Default Value
3rd option

在上面的代码片段中,dd没有键4或键5,因此它输出了一个默认值,这是我们在helper函数中配置的。这比原始字典要好得多,在原始字典中,如果key不存在就会抛出KeyError。由此可见,defaultdict更像是一个switch case语句,在这里我们可以避免复杂的if-elif-elif-else块。

另一个让我印象深刻的例子是:

>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
...     food_count[food] += 1 # increment element's value by 1
...
defaultdict(<type 'int'>, {'eggs': 1, 'spam': 7})
>>>

如果我们尝试访问鸡蛋和垃圾邮件以外的任何物品,我们将得到0的计数。