Python 浮点值作为字典键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23721230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:22:49  来源:igfitidea点击:

Float values as dictionary key

pythondictionaryfloating-pointkey

提问by Moritz

I am developing a class for the analysis of microtiter plates. The samples are described in a separate file and the entries are used for an ordered dictionary. One of the keys is pH, which is usually given as float. e.g 6.8

我正在开发一个用于分析微量滴定板的课程。样本在单独的文件中描述,条目用于有序字典。关键之一是 pH 值,通常以浮点数形式给出。例如 6.8

I could import it as decimal with Decimal('6.8')in order to avoid a float as dict key. Another solution would be to replace the dot with e.g p like 6p8 or to write 6p8 in my sample description and therefore eliminating the problem at the beginning. But this would cause troubles later on since i cannot plot pH of 6p8 in my figures.

我可以将其导入为十进制,Decimal('6.8')以避免浮点数作为字典键。另一种解决方案是用例如 p 替换点,如 6p​​8 或在我的示例描述中写入 6p8,从而在开始时消除问题。但这会在以后造成麻烦,因为我无法在我的数字中绘制 6p8 的 pH 值。

How would you solve this issue?

你会如何解决这个问题?

采纳答案by John La Rooy

There's no problem using floats as dict keys.

使用浮点数作为字典键没有问题。

Just round(n, 1)them to normalise them to your keyspace. eg.

只是将round(n, 1)它们标准化为您的密钥空间。例如。

>>> hash(round(6.84, 1))
3543446220
>>> hash(round(6.75, 1))
3543446220

回答by Reblochon Masque

Perhaps you want to truncate your float prior to using is as key?

也许您想在使用 is 作为关键之前截断您的浮点数?

Maybe like this:

也许是这样的:

a = 0.122334
round(a, 4)       #<-- use this as your key?

Your key is now:

你的钥匙现在是:

0.1223           # still a float, but you have control over its quality

You can use it as follows:

您可以按如下方式使用它:

dictionary[round(a, 4)]   

to retrieve your values

检索您的值

回答by minkwe

Another option would be to use tuples:

另一种选择是使用元组:

dictionary = {(6.8,): 0.3985}
dictionary[(6.8,)]

Then Retrieving the values later for plotting is easily done with something like

然后稍后检索用于绘图的值很容易使用类似的方法完成

points = [(pH, value) for (pH,), value in dictionary.items()]
    ...

回答by zyy

Another quick option is to use strings of the float

另一个快速选择是使用浮点数的字符串

a = 200.01234567890123456789
b = {str(a): 1}
for key in b:
    print(float(key), b[key])

would print out

会打印出来

(200.012345679, 1)

notice agets truncatedat tenth digit after decimal point.

通知在小数点后的第十位a截断