Python 字典无法识别浮点键

Python 字典无法识别浮点键,python,numpy,dictionary,floating-point,key,Python,Numpy,Dictionary,Floating Point,Key,我有一个名为G的字典。当我输入G.keys()时,输出的示例如下: >>> G.keys () [(1490775.0, 12037425.0), (1493775.0, 12042675.0), (1481055.0, 12046305.0), (1503105.0, 12047415.0), (1488585.0, 12050685.0), (1483935.0, 12051405.0),... 当我使用操作键入G时,结果为假 >>> (1490775.

我有一个名为G的字典。当我输入
G.keys()
时,输出的示例如下:

>>> G.keys ()
[(1490775.0, 12037425.0), (1493775.0, 12042675.0), (1481055.0, 12046305.0), (1503105.0, 12047415.0), (1488585.0, 12050685.0), (1483935.0, 12051405.0),...
当我使用操作
键入G
时,结果为假

>>> (1490775.0, 12037425.0) in G
False
为什么我的字典不能识别我的钥匙

>>> type (G.keys()[0])
<type 'numpy.void'>
>>> type (G.keys()[0][0])
<type 'numpy.float64'>
>>> type (G.keys()[0][1])
<type 'numpy.float64'>
type(G)
<type 'dict'>
>类型(G.keys()[0])
>>>类型(G.keys()[0][0])
>>>类型(G.keys()[0][1])
类型(G)

在这种情况下,您可能就是这样到达的:

import numpy as np
arr = np.array([(1490775.0, 12037425.0)], dtype=[('foo','<f8'),('bar','<f8')])
arr.flags.writeable = False

G = dict()
G[arr[0]] = 0

print(type(G.keys()[0]))
# <type 'numpy.void'>

print(type(G.keys()[0][0]))
# <type 'numpy.float64'>

print(type(G.keys()[0][1]))
# <type 'numpy.float64'>

print(type(G))
# <type 'dict'>
但是numpy.void实例是
G
中的一个键:

print((1490775.0, 12037425.0) in G)
# False
print(arr[0] in G)
# True

您最好不要使用
numpy.voids
作为键。相反,如果您确实需要dict,则可能首先将数组转换为列表:

In [173]: arr.tolist()
Out[173]: [(1490775.0, 12037425.0)]
In [174]: G = {item:0 for item in arr.tolist()}

In [175]: G
Out[175]: {(1490775.0, 12037425.0): 0}

In [176]: (1490775.0, 12037425.0) in G
Out[176]: True

浮点数神在吃它吗?@thefourtheye我本想说一些关于使用浮点数作为dict键的事情,但我认为你总结得很好!我允许自己编辑标题和标签,以提高有相同问题的人不会再重复这个问题的可能性。每天至少有十几个类似的问题被问到……你能告诉我们什么是
类型(G.keys()[0])
,什么是
类型(G.keys()[0][0])
类型(G.keys()[0][1])
吗?如果这些真的是Python浮点和Python元组,那么您不应该看到这种行为?