Python defaultdict 的默认值是 1?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30356892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:18:51  来源:igfitidea点击:

defaultdict with default value 1?

pythondefaultdict

提问by chancyWu

I am new to python, and i read some code snippet from some place. It's an implementation of counting sort.

我是 python 的新手,我从某个地方阅读了一些代码片段。它是计数排序的实现。

The code is as below:

代码如下:

from collections import defaultdict
def sort_colors(A):
    ht = {}                        # a hash map
    ht = defaultdict(lambda:0, ht) # with default value 1
    for i in A:
         ht[i] += 1
    ret = []
    for k in [0, 1, 2]:
        ret.extend([k]*ht[k])
    return ret

As in the first two lines of the func, it's

与 func 的前两行一样,它是

ht = {}
ht = defaultdict(lambda:0, ht)

I am not quite clear about this initialization.Could you kindly help me figure it out? and also, Shall we just replace these two lines with following?

这个初始化我不是很清楚。你能帮我弄清楚吗?而且,我们是否应该用以下内容替换这两行?

ht = defaultdict(int) # default value 0

采纳答案by rafaelc

Short answer (as per Montaro's answer below)

简短回答(根据下面蒙塔罗的回答)

defaultdict(lambda:1)


Long answer on how defaultdicts work

关于如何defaultdict工作的长答案

ht = {}
ht = defaultdict(lambda:0, ht)

defaultdicts are different from dictin that when you try to access a regular dictwith a key that does not exists, it raises a KeyError.
defaultdict, however, doesn't raise an error: it creates the key for you instead. With which value? With the return of the callableyou passed as an argument. In this case, every new keys will be created with value 0(which is the return of the simple lambdafunction lambda:0), which also happens to be the same return of int(), so in this case, there would be no difference in changing the default function to int().

defaultdicts 的不同之处dict在于,当您尝试使用dict不存在的键访问常规时,它会引发KeyError.
defaultdict,但是,不会引发错误:而是为您创建密钥。用哪个值?随着callable你作为参数传递的返回。在这种情况下,每个新键都将使用 value 创建0(这是简单lambda函数的返回lambda:0),这也恰好是 的相同返回int(),因此在这种情况下,将默认函数更改为 没有区别int()

Breaking down this line in more detail: ht = defaultdict(lambda:0, ht)

更详细地分解这一行: ht = defaultdict(lambda:0, ht)

The first argument is a function, which is a callable object. This is the function that will be called to create a new value for an inexistent key. The second argument, htis optional and refers to the base dictionary that the new defaultdictwill be built on. Therefore, if hthad some keys and values, the defaultdictwould also have these keys with the corresponding values. If you tried to access these keys, you would get the old values. However, if you did not pass the base dictionary, a brand new defaultdictwould be created, and thus, all new keys accessed would get the default value returned from the callable.
(In this case, as htis initially an empty dict, there would be no difference at all in doing ht = defaultdict(lambda:0), ht = defaultdict(int)or ht = defaultdict(lambda:0, ht): they would all build the same defaultdict.

第一个参数是一个函数,它是一个可调用的对象。将调用此函数为不存在的键创建新值。第二个参数ht是可选的,指的是新的基础字典defaultdict。因此,如果ht有一些键和值,defaultdict也会有这些键和相应的值。如果您尝试访问这些键,您将获得旧值。但是,如果您没有传递基本字典,defaultdict则会创建一个全新的字典,因此,所有访问的新键都将获得从可调用对象返回的默认值。
(在这种情况下,因为ht最初是空的dict,所以在做时根本没有区别ht = defaultdict(lambda:0)ht = defaultdict(int)或者ht = defaultdict(lambda:0, ht): 他们都会构建相同的defaultdict

回答by Montaro

I think you can just pass a lambda function that returns 1

我认为你可以只传递一个返回的 lambda 函数 1

d = defaultdict(lambda:1)