问题描述
我正在尝试在两个 dict
之间进行除法运算,并且总是得到 int
结果,但我期望得到 float
。
这是怎么回事:
test_dict1 = {'gfg': 20,'is': 24,'best': 30}
test_dict2 = {'gfg': 7,'is': 7,'best': 7}
res = {key: test_dict1[key] // test_dict2.get(key,0)
for key in test_dict1.keys()}
res = {'best': 4,'gfg': 2,'is': 3}
解决方法
您的运营商有问题://
。 python 中的 //
运算符返回除法的商。以“最佳”键为例,30 // 7 => 4Q,2R。您正在寻找的只是 /
运算符。 30/7 = 4.285.....
更正:
res = {
key: test_dict1[key] / test_dict2.get(key,0) for key in test_dict1.keys()
}