考虑 Python 中的这种划分:
Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
这是故意的吗?我强烈记得返回的早期版本int/int = int
。我该怎么办?是否有新的除法运算符或者我必须始终转换?
考虑 Python 中的这种划分:
Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
这是故意的吗?我强烈记得返回的早期版本int/int = int
。我该怎么办?是否有新的除法运算符或者我必须始终转换?
看看PEP-238:改变除法运算符
// 运算符将可用于明确地请求楼层划分。
哎呀,马上找到了2//2
。这将输出一个 int 而不是 float。
在 Python 2.7 中:默认情况下,除法运算符将返回整数输出。
要获得双倍结果,请将被除数或除数乘以 1.0。
100/35 => 2 # Expected is 2.857142857142857
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857
在 Python 3 中
// => used for integer output
/ => used for double output
100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0 # Floating-point result if the divisor or dividend is real
接受的答案已经提到PEP 238。我只想为那些对正在发生的事情感兴趣而无需阅读整个 PEP 的人快速了解一下幕后情况。
Python 将 、 和 等运算符映射+
到特殊函数,例如,-
等价于*
/
a + b
a.__add__(b)
关于 Python 2 中的除法,默认情况下只有/
哪个映射到__div__
,结果取决于输入类型(例如int
, float
)。
Python 2.2 引入了这个__future__
特性division
,它通过以下方式改变了除法语义(TL;PEP 238 的 DR):
/
__truediv__
必须“返回除法数学结果的合理近似值”的映射(引自 PEP 238)//
映射到__floordiv__
,它应该返回下限结果/
在 Python 3.0 中,PEP 238 的更改成为默认行为,Python 的对象模型中没有更多特殊方法__div__
。
如果您想在 Python 2 和 Python 3 中使用相同的代码,请使用
from __future__ import division
并坚持 and 的 PEP 238/
语义//
。
根据 Python 3 文档,当 Python 除以整数时,尽管预期为整数,但仍会生成浮点数。
要专门打印整数,请使用floor division method
. 地板除法是四舍五入零并删除小数点。Represented by //
因此,使用 2/2 而不是2//2
__future__
无论使用 Python 2 还是 Python 3,您都可以导入除法。