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 调用 x[k] 时(例如像 v=x[k] 这样的语句),键值pair (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?
你呢?似乎默认工厂会创建一个默认值为 0 的 defaultdict.但这具体意味着什么?我试图在 Python shell 中玩弄它,但无法弄清楚它到底是什么.
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.
推荐答案
我认为第一行的意思是当我为不存在的键
k
调用x[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
.
即,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屋!