gpt4 book ai didi

python - 我如何在 Python2 中对 `round` 函数进行 future 验证?

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:59 25 4
gpt4 key购买 nike

round 从 future 导入时,它的行为与 Python3 round 函数不同。具体来说,它不支持负数舍入。

在 Python3 中:

>>> round(4781, -2)
4800

在 Python2 中:

>>> from builtins import round
>>> round(4781, -2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/future/builtins/newround.py", line 33, in newround
raise NotImplementedError('negative ndigits not supported yet')
NotImplementedError: negative ndigits not supported yet

可能的解决方案包括负舍入的错误处理、编写我自己的 round 函数等。应该如何处理? (含蓄地,我要求最佳实践,大多数 Pythonic,被社区接受等)

最佳答案

我打算建议您的自定义函数想法,这样您就可以确保它始终按照您的意愿行事,但这似乎是一个特殊(奇怪)的情况,如果我使用future.builtin.round() 我明白了

python 3.6:

>>> round(4781, -2)
4800

和 Python 2.7:

>>> round(4781, -2)
4800.0

似乎只是 future.builtins 以某种方式损坏了;在这种情况下,您应该避免使用 future.builtins.round() 函数。请注意,py3 round() 返回一个整数,而 py2 round() 返回一个 float ,但这似乎是两种股票实现之间的唯一区别(对于简单的舍入操作例如给出的示例)。

关于python - 我如何在 Python2 中对 `round` 函数进行 future 验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48359884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com