dict.fromkeys对浮点键没有预期效果

时间:2016-06-05 21:14:47

标签: python list dictionary

我有一个像这样的Python列表:

import numpy

thresholds = numpy.linspace(0.7, 0.9, 21)

print(thresholds)

[0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9]

当我尝试通过执行dict从此列表创建dict.fromkeys()时,结果与预期不符:

thresholds = dict.fromkeys(numpy.linspace(0.7, 0.9, 21))

print(thresholds)

{0.69999999999999996: None, 0.70999999999999996: None, 0.84999999999999998: None, 0.83000000000000007: None, 0.81000000000000005: None, 0.79000000000000004: None, 0.77000000000000002: None, 0.78000000000000003: None, 0.72999999999999998: None, 0.83999999999999997: None, 0.71999999999999997: None, 0.89000000000000001: None, 0.87: None, 0.80000000000000004: None, 0.76000000000000001: None, 0.90000000000000002: None, 0.73999999999999999: None, 0.88: None, 0.85999999999999999: None, 0.82000000000000006: None, 0.75: None}

我期待这样的dict

{0.7: None, 0.71: None, 0.85: None, 0.83: None, 0.81: None, 0.79: None, 0.77: None, 0.78: None, 0.73: None, 0.84: None, 0.72: None, 0.90: None, 0.87: None, 0.80: None, 0.76: None, 0.90: None, 0.74: None, 0.88: None, 0.86: None, 0.82: None, 0.75: None}

为什么我不能在最终dict中得到舍入值,我该如何纠正?

2 个答案:

答案 0 :(得分:2)

如果您对浮点表示感到不安,则应尝试将值转换为decimal类型。否则,就放手吧。

print('%1.17f' % 0.7)
print('%1.2f' % 0.7)

0.69999999999999996
0.70

答案 1 :(得分:2)

您最好将浮点数从numpy.linspace转换为字符串。直接使用floats作为python中的字典键是一个可怕的想法,原因与精度相关(你不能打赌100%精度)和浮点数的评估方式。

thresholds = numpy.linspace(0.7, 0.9, 21)

# freezing the precision of your floating point numbers
stringified_thresholds = [str(i) for i in thresholds]

thresholds_dict = dict.fromkeys(stringified_thresholds)

您可以从这里继续工作。