字典无法识别浮点键

2024-05-07 05:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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),...

当我使用操作key in G时,结果是false。在

^{pr2}$

为什么我的字典没有认出我的钥匙?在

>>> 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'>

Tags: keyinnumpyfalse示例字典typekeys
1条回答
网友
1楼 · 发布于 2024-05-07 05:20:19

你可能就是这样来的:

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'>

浮点元组不是G中的键:

^{pr2}$

但是空荡荡的实例是G中的键:

print(arr[0] in G)
# True

您最好不要使用numpy.voids作为键。相反,如果您确实需要dict,那么可以先将数组转换为list:

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

相关问题 更多 >