在别人的代码中,我读到了以下两行:
x = defaultdict(lambda: 0)
y = defaultdict(lambda: defaultdict(lambda: 0))
由于 defaultdict 的参数是一个默认工厂,我认为第一行的意思是当我为一个不存在的键 k 调用 x[k] 时(例如像 v=x[k] 这样的语句),键值pair (k,0) 将被自动添加到字典中,就像首先执行语句 x[k]=0 一样。我说的对吗?
那你呢?似乎默认工厂将创建一个默认为 0 的 defaultdict。但这具体意味着什么?我尝试在 Python shell 中使用它,但无法弄清楚它到底是什么。
最佳答案
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.
没错。这个写的比较通俗
x = defaultdict(int)
在y
的情况下,当你做y["ham"]["spam"]
时,键"ham"
如果不存在,则插入到 y
中。与之关联的值变成 defaultdict
,其中自动插入 "spam"
值 0
。
即,y
是一种“两层”defaultdict
。如果 "ham"不在 y
中,那么评估 y["ham"]["spam"]
就像在做
y["ham"] = {}
y["ham"]["spam"] = 0
就普通的dict
而言。
关于Python defaultdict 和 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8419401/