为什么浮点字典键可以覆盖具有相同值的整数键? [英] Why can a floating point dictionary key overwrite an integer key with the same value?
问题描述
我正在通过 http://www.mypythonquiz.com 和 问题 #45 要求输出以下代码:
混淆 = {}混乱[1] = 1混淆['1'] = 2混乱[1.0] = 4总和 = 0对于混乱中的 k:总和 += 混淆[k]打印总和
输出为 6
,因为键 1.0
替换了 1
.这对我来说有点危险,这是一个有用的语言功能吗?
你应该考虑到 dict
旨在根据逻辑数值存储数据,而不是你如何表示它.
int
s 和 float
s 之间的区别确实只是一个实现细节,而不是概念上的.理想情况下,唯一的数字类型应该是具有无限精度甚至子统一性的任意精度数字……然而,这很难在不陷入困境的情况下实现……但这可能是 Python 未来唯一的数字类型.>
因此,虽然由于技术原因有不同的类型,Python 会尝试隐藏这些实现细节,并且 int
->float
转换是自动的.
如果在 Python 程序中 if x == 1: ...
在 x
是 时不会被采用,那会更令人惊讶>float
值为 1.
请注意,在 Python 3 中,1/2
的值为 0.5
(两个整数的除法),并且类型 long
和非 unicode 字符串已被删除,同样试图隐藏实现细节.
I'm working through http://www.mypythonquiz.com, and question #45 asks for the output of the following code:
confusion = {}
confusion[1] = 1
confusion['1'] = 2
confusion[1.0] = 4
sum = 0
for k in confusion:
sum += confusion[k]
print sum
The output is 6
, since the key 1.0
replaces 1
. This feels a bit dangerous to me, is this ever a useful language feature?
You should consider that the dict
aims at storing data depending on the logical numeric value, not on how you represented it.
The difference between int
s and float
s is indeed just an implementation detail and not conceptual. Ideally the only number type should be an arbitrary precision number with unbounded accuracy even sub-unity... this is however hard to implement without getting into troubles... but may be that will be the only future numeric type for Python.
So while having different types for technical reasons Python tries to hide these implementation details and int
->float
conversion is automatic.
It would be much more surprising if in a Python program if x == 1: ...
wasn't going to be taken when x
is a float
with value 1.
Note that also with Python 3 the value of 1/2
is 0.5
(the division of two integers) and that the types long
and non-unicode string have been dropped with the same attempt to hide implementation details.
这篇关于为什么浮点字典键可以覆盖具有相同值的整数键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!