在使用 python 3.6.8 的 Linux 服务器上遇到以下问题。 使用简单浮点变量的 Json.dumps() 调用在每次运行中给出不同的结果。
$ python3
Python 3.6.8 (default, Oct 8 2020, 16:04:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.200)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> print(json.dumps(float(2341)))
2373.0
>>> print(json.dumps(float(2341)))
2342.28
>>> print(json.dumps(float(2341)))
2342.28
>>> print(json.dumps(float(2341)))
2342.3121632
>>> print(json.dumps(float(2341)))
2342.28
>>> print(json.dumps(float(2341)))
2341.0
>>> print(json.dumps(float(2341)))
2341.0
>>> print(json.dumps(float(2341)))
2373.0
>>> print(json.dumps(float(2341)))
2342.28
>>> print(json.dumps(float(2341)))
2342.28
>>> print(json.__file__)
/usr/lib64/python3.6/json/__init__.py
>>> exit()
$ which python3
/usr/bin/python3
$
“Int”变量没有问题。 已验证 python 包文件夹中的文件,看起来都完好无损。 没有发现与服务器内存/CPU 相关的问题。 重新启动服务器/重新安装 python 包目前不是可行的选择。 需要一些指导来进一步调试/修复此问题。
---- 编辑 ---- print(float(x)) 也出现问题
$ python3
Python 3.6.8 (default, Oct 8 2020, 16:04:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44.0.200)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print(float(2341))
2341.0
>>> print(float(2341))
2341.0
>>> print(float(2341))
2342.28
>>> print(float(2341))
2342.312
>>> print(float(2341))
2342.3121632
>>> print(float(2341))
2342.28
>>> print(float(2341))
2342.312
>>> print(float(2341))
2342.28
>>> print(float(2341))
2342.28
>>> print(float(2341))
2342.312
>>> print(float(2341))
2342.28
>>> print(float(2341))
2341.0
>>> print(float(2341))
2373.0
>>> exit()
----- 编辑 ---- 不同风格的打印+ float 。同样的问题。
>>> x = float(2341)
>>> for _ in range(20): print(x)
...
2342.312
2342.28
2342.28
2342.28
2342.312
2342.312
2373.0
2342.28
2373.0
2373.0
2373.0
2373.0
2342.3121632
2342.3121632
2373.0
2342.28
2373.0
2342.28
2342.28
2373.0
>>>
>>> for _ in range(20): print(2341.0)
...
2373.0
2342.28
2342.312
2342.28
2342.28
2342.28
2342.28
2373.0
2342.28
2342.28
2373.0
2373.0
2342.28
2373.0
2342.312
2373.0
2373.0
2342.28
2342.3121632
2342.3121632
>>>
>>> import builtins
>>> print(builtins.float(2341))
2342.28
>>> print(builtins.float(2341))
2373.0
>>> print(builtins.float(2341))
2342.3121632
>>> print(builtins.float(2341))
2373.0
>>>
最佳答案
这似乎不是 json.dumps()
的正常行为。因此,最好的做法是确保一切正常工作并重新安装导致问题的任何软件包或模块。具体来说,尝试重新安装基本 Python 解释器,看看 print(json.dumps(2341.0))
和其他类似表达式会发生什么情况。此外,如果所有其他方法都失败,您始终可以使用第三方库,例如 orjson .
关于Python print 和 json.dumps 更改浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70818601/