Python defaultdict和lambda [英] Python defaultdict and lambda
问题描述
在别人的代码中,我读了以下两行:
In someone else's code I read the following two lines:
x = defaultdict(lambda: 0)
y = defaultdict(lambda: defaultdict(lambda: 0))
由于defaultdict的参数是默认工厂,我认为第一行意味着当我为不存在的密钥k(例如像v = x [k]的语句)调用x [k]时,键值对(k,0)将被自动添加到字典,好像首先执行语句x [k] = 0。我是否正确?
As the argument of defaultdict is a default factory, I think the first line means that when I call x[k] for a nonexistent key k (such as a statement like v=x[k]), the key-value pair (k,0) will be automatically added to the dictionary, as if the statement x[k]=0 is first executed. Am I correct?
那么y呢?看来默认工厂将创建一个默认为0的defaultdict。但是具体是什么意思?
And what about y? It seems that the default factory will create a defaultdict with default 0. But what does that mean concretely? I tried to play around with it in Python shell, but couldn't figure out what it is exactly.
推荐答案
我认为第一行意味着当我为
x [k]
调用不存在的键k
例如v = x [k]
的语句),键值对(k,0)
将自动添加到字典中,如同第一次执行语句x [k] = 0
。
I think the first line means that when I call
x[k]
for a nonexistent keyk
(such as a statement likev=x[k]
), the key-value pair(k,0)
will be automatically added to the dictionary, as if the statementx[k]=0
is first executed.
没错。这是更惯用的写法
That's right. This is more idiomatically written
x = defaultdict(int)
在 y
的情况下,当您执行 y [ham] [ spam]
时,ham
中的键插入 y
存在。与其关联的值变为 defaultdict
,其中spam
自动插入值 0
。
In the case of y
, when you do y["ham"]["spam"]
, the key "ham"
is inserted in y
if it does not exist. The value associated with it becomes a defaultdict
in which "spam"
is automatically inserted with a value of 0
.
Ie, y
是一种 defaultdict
。如果ham不在y
,则评估 y [ham] [spam]
I.e., y
is a kind of "two-tiered" defaultdict
. If "ham" not in y
, then evaluating y["ham"]["spam"]
is like doing
y["ham"] = {}
y["ham"]["spam"] = 0
按照普通 dict
。
这篇关于Python defaultdict和lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!