Counter(dict1)+ Counter(dict2)提供了错误的答案

时间:2019-12-22 03:15:00

标签: python

from Q import *
from collections import Counter

#Q1, Q2 are dictionaries which are imported from Q.py
Q1 = Counter(Q1)
Q2 = Counter(Q2)
Q = Q1+Q2

ene = 0.0
for k,v in Q1.items():
    ene += v
print(ene)

ene = 0.0
for k,v in Q2.items():
    ene += v
print(ene)

ene = 0.0
for k,v in Q.items():
    ene += v
print(ene)

然后运行代码,我得到了输出:

-6.81022233745
0.0
39542.4622651

为什么最后一行不等于前两行的总和? 请帮忙!谢谢。

1 个答案:

答案 0 :(得分:1)

来自documentation

  

多重集方法仅设计用于具有正值的用例。输入可以为负或零,但仅创建具有正值的输出。没有类型限制,但是值类型需要支持加,减和比较。

SELECT LocationMaster.LocationName , COALESCE(MHReporting.DHE, 0) AS DHE , ... FROM LocationMaster LEFT JOIN (SELECT Location , AttendanceDate , SUM(DHE) AS DHE , SUM(Contractors) AS Contractors , SUM(ADNOCContractors) AS ADNOCContractors FROM MHReporting WHERE MHReporting.AttendanceDate = [DesiredDate] GROUP BY Location, AttendanceDate) MHReporting ON LocationMaster.ID = MHReporting.Location LEFT JOIN (SELECT ... 运算符算作多集方法–甚至不需要涉及浮点数:

+

另一个选择可以是>>> Counter() + Counter({'a': -5}) Counter()

defaultdict(float)