简体   繁体   English

字典无法识别浮点键

[英]Dictionary not recognizing floating point keys

I have a dictionary called G. When I enter G. keys () , an example of the output is: 我有一个名为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),...

When I use the operation key in G the result is false. 当我key in G使用操作key in G ,结果为false。

>>> (1490775.0, 12037425.0) in G
False

Why isn't my dictionary recognizing my keys? 为什么我的字典不能识别我的密钥?

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

This might be how you arrived in this situation: 这可能是你到达这种情况的方式:

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

A tuple of floats is not a key in G : 一个浮点元组不是G的关键:

print((1490775.0, 12037425.0) in G)
# False

But the numpy.void instance is a key in G : 但是numpy.void实例是G一个关键:

print(arr[0] in G)
# True

You will probaby be better off not using numpy.voids as keys. 你不用使用numpy.voids作为密钥就可以了。 Instead, if you really need a dict, then perhaps convert the array to a list first: 相反,如果你真的需要一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM