3

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

在 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,被社区接受等)

4

1 回答 1

3

我打算建议您的自定义功能想法,以便您可以确保它始终执行您想要的操作,但这似乎是一个特殊(奇怪)的情况,如果我使用future.builtin.round()我会得到

蟒蛇 3.6:

>>> round(4781, -2)
4800

和 Python 2.7:

>>> round(4781, -2)
4800.0

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

于 2018-01-20T19:37:23.933 回答