【问题标题】:Implement Python 3's round function in Python 2.7在 Python 2.7 中实现 Python 3 的 round 函数
【发布时间】:2013-08-08 00:38:52
【问题描述】:

我在使用 Python 2.7 的 Google-App-Engine 项目中使用了一些用 Python 3 编写的旧代码。 Python 3 和 Python 2 中不同的 round() 算法让我很头疼。在 Python 2.7 中实现 Python 3 的 round() 方法有什么方便的方法吗?

另一个问题:Python 2 和 Python 3 处理整数运算的方式完全不同。例如,以下语句在 Python 2 和 3 中具有不同的输出:

2/4   # 0 in Python 2, 0.5 in Python 3
round(3/2)  
math.ceil(0.5)   # 1.0 in Python 2, 1 in Python 3

有什么简单的方法可以将代码从 Python 3 转换为 Python 2,同时保持行为完全相同?

谢谢!

【问题讨论】:

  • 在py2.x中使用from __future__ import division获取py3.x的除法行为。

标签: python python-2.7 python-3.x google-app-engine rounding


【解决方案1】:

银行家的四舍五入在future 中实现。可以使用 __future__ 导入将浮点除法设为默认值。

from __future__ import division
from future.modified_builtins import round

【讨论】:

  • 我在 Python 2.7 中尝试了“from future.modified_builtins import round”,结果 ImportError 说:没有名为 future.modified_builtins 的模块。我无法获得有关此“future.modified_builtins”库的有用结果。这里有什么问题吗?
  • 你试过先安装吗?
  • 我没有专门安装它。仅限标准 Python 2.7 和 GAE 库。
  • 谢谢。我在这里得到它:github.com/edschofield/python-future/blob/master/future/… 我认为它包含在标准 2.7 发行版中。
  • @TaoChen 链接失效
猜你喜欢
  • 2013-03-03
  • 2013-03-21
  • 2020-06-19
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 2013-02-13
  • 2023-03-31
  • 2018-10-20
相关资源
最近更新 更多