Skip to main content
 首页 » 编程设计

python之创建默认值为零 (0) 的 defaultdict

2025年05月04日14lyj

<分区>

类似于this question我想创建一个默认值为零的 collections.defaultdict 来计算元组列表的元素:

tuples = [('foo', 5), ('foo', 5), ('bar', -5), ('bar', -2)] 
totals = defaultdict(0) 
for t in tuples: 
    totals[t[0]] += t[1] 

但是 defaultdict(0) 说:

TypeError: first argument must be callable 

我应该如何创建“可赎回”零?