Python defaultdict 和 lambda

标签 python collections defaultdict

在别人的代码中,我读到了以下两行:

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 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.

没错。这个写的比较通俗

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/

相关文章:

python - 如果在 defaultdict 中找不到键,则返回最大键的值

c# - 如何使用 C# 中的键对 NameValueCollection 进行排序?

java - Java 中的快速字符串集合

c# - 使用反射从类列表的属性中获取值

python - 如何获取 defaultdict 中值的类型

python - 根据值过滤defaultdict

python - SQLAlchemy 查询返回无

python - 在 Python 中是否可以装饰一个函数以便记录它的开始和结束?

python - 使用 IPython 运行脚本时解析参数

python - Plotly Scattermapbox : Is there a way to include some text above and below the markers?