gpt4 book ai didi

python collections.defaultdict 列表长度为 2

转载 作者:太空狗 更新时间:2023-10-30 01:51:44 32 4
gpt4 key购买 nike

我有这样一种情况,一个键有两个值,这两个值将在程序期间更新。更具体地说,从空字典 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com