作为 this 的后续使用 Counter() 解决的问题,我遇到了一个看起来很容易解决的新问题 - 但我无法让它工作。
我正在尝试使用 Counter() 对一系列 dict 条目求和,如果总和为正整数,该条目有效,但如果总和为负整数,则返回空元素。我能够找到 this在解释 Counter() 本身旨在计算而不是求和时,答案是正确的。
我可以重新创建示例并使其运行,但是使用 django 查询集,当与 Counter() 方法结合使用时,会生成一个更复杂的字典,如下所示。
totals = {
'sumthing_a': Counter({'total': 48000}),
'sumthing_b': Counter({'total': 39050}),
'sumthing_c': Counter({'total': 8950}),
'sumthing_d': Counter({'total': 10000}),
'sumthing_e': Counter({'total': 17200}),
'sumthing_f': Counter({'total': 17750}),
'sumthing_g': Counter({'total': 30450}),
}
我试过以下变体:
totals.update({'sumthing_e': Counter({'total': 300})})
用 300 替换原来的 17200 而不是添加它们。
我也试过:
totals['sumthing_e'].update({'sumthing_e': Counter({'total': 300})})
抛出:+ 不支持的操作数类型:'Counter' 和 'int'
.update() 的文档指出:
Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs.
并且有一个文档注释指出:
For in-place operations such as c[key] += 1, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for update() and subtract() which allow negative and zero values for both inputs and outputs.
这让我相信,如果编码正确,我尝试做的事情是可能的。最后的结果应该是能够有一个负数——举个例子:
totals = {
'sumthing_a': Counter({'total': 48000}),
'sumthing_b': Counter({'total': -40503}),
'sumthing_c': Counter({'total': 8950}),
'sumthing_d': Counter({'total': 10000}),
'sumthing_e': Counter({'total': -58462}),
'sumthing_f': Counter({'total': 17750}),
'sumthing_g': Counter({'total': 30450}),
}
请您参考如下方法:
查看 totals['sumthing_e'] 的类型
In [13]: type(totals['sumthing_e'])
Out[13]: collections.Counter
然后您尝试通过普通字典更新它 {'sumthing_e': Counter({'total': 300})}
所以如果你想在你的工作示例中重置计数器,你应该这样做:
totals['sumthing_e'] = Counter({'total': 300})
但是如果你想更新你的计数器你应该这样做:
In [15]: totals['sumthing_e'].update(Counter({'total': 300}))
In [16]: totals['sumthing_e']
Out[16]: Counter({'total': 600})
In [17]: totals['sumthing_e'].update(Counter({'total': 300}))
In [18]: totals['sumthing_e']
Out[18]: Counter({'total': 900})
In [19]: totals['sumthing_e'].update(Counter({'total': -200}))
In [20]: totals['sumthing_e']
Out[20]: Counter({'total': 700})
