简体   繁体   English

defaultdict 的默认值是 1?

[英]defaultdict with default value 1?

I am new to python, and i read some code snippet from some place.我是 python 的新手,我从某个地方阅读了一些代码片段。 It's an implementation of counting sort.它是计数排序的实现。

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

Short answer (as per Montaro's answer below)简短回答(根据下面蒙塔罗的回答)

defaultdict(lambda:1)

Long answer on how defaultdict s work关于defaultdict如何工作的长答案

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

defaultdict s are different from dict in that when you try to access a regular dict with a key that does not exists, it raises a KeyError . defaultdict s 与dict不同之处在于,当您尝试使用不存在的键访问常规dict时,它会引发KeyError
defaultdict , however, doesn't raise an error: it creates the key for you instead.但是, defaultdict不会引发错误:而是为您创建密钥。 With which value?用哪个值? With the return of the callable you passed as an argument.随着callable的返回,您作为参数传递。 In this case, every new keys will be created with value 0 (which is the return of the simple lambda function 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() .在这种情况下,每个新键都将创建为值为0 (这是简单的lambda函数lambda:0的返回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, ht is optional and refers to the base dictionary that the new defaultdict will be built on.第二个参数ht是可选的,指的是新的defaultdict将在其上构建的基本字典。 Therefore, if ht had some keys and values, the defaultdict would also have these keys with the corresponding values.因此,如果ht有一些键和值, defaultdict也会有这些键和相应的值。 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 defaultdict would be created, and thus, all new keys accessed would get the default value returned from the callable.但是,如果您没有传递基本字典,则会创建一个全新的defaultdict ,因此,所有访问的新键都将获得从可调用对象返回的默认值。
(In this case, as ht is 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最初是一个空的dict ,因此在执行ht = defaultdict(lambda:0)ht = defaultdict(int)ht = defaultdict(lambda:0, ht)根本没有区别:它们都会构建相同的defaultdict

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

d = defaultdict(lambda:1)

Equivalent to @Montaro's answer:相当于@Montaro 的回答:

def a():
    return 1

d = defaultdict(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM