python collections.defaultdict 列表长度为 2

标签 python defaultdict

我有这样一种情况,一个键有两个值,这两个值将在程序期间更新。 更具体地说,从空字典 d = {} 开始,我想做这样的事情: d[a][0] += 1d[a][1] += 1 其中 a 是浮点类型程序运行时也发现了。我可以对 d = defaultdict(list([0,0])) 的效果做些什么吗(这会出错)。我希望字典中的默认值是两个元素的列表。我该怎么做?

最佳答案

刚刚阅读the documentation :

If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

也就是说,defaultdict 的参数不是默认值,它是一个被调用以产生默认值的函数。所以就这样做:

defaultdict(lambda: [0,0])

(无需显式使用 list([0,0])[0,0] 已经是一个列表。)

关于python collections.defaultdict 列表长度为 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15060530/

相关文章:

python - 将 Python 字典拆分为多个键,将值平均分配

python:带有非默认参数的defaultdict

python - 使用 defaultdict 搜索键及其值

python - pyodbc.OperationalError TCP 提供程序 : Error code 0x2746 & TCP Provider: Error code 0x20 (32)

python - 使用defaultdict时出现按键错误

python - 列表理解转换

python - 将 defaultdict(list) 写入文件

python - pandas - 数据框中出现的唯一行数

python - vim 在函数和类定义下添加自动 sphinx 注释

python - Django 模型 : How to combine the reverse access sets from two foreignkey fields?