为了生成 Numpy 索引,我需要将 float
舍入为 int
。
在 Python 2.7 中,舍入一个 float
得到一个 float
:
>>> round(2.7)
3.0
在 Python 3.5 中,返回一个 int
:
>>> round(2.7)
3
np.round()
总是返回一个 float 。
int(round(2.7))
是以 Python 2/3 兼容方式舍入为整数的规范方法吗?
最佳答案
int(round(2.7))
适用于两个版本。这里提出了一个类似的问题,但仅适用于 Python 2.7:
Python 2.7: round number to nearest integer
- 所以我会使用 int(round(x))
关于python - 以 Python2 和 Python3 兼容的方式舍入 float 并将其转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371424/