使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
当前回答
//是楼层划分。它总是会给你结果的整数底。另一种是“常规”除法。
其他回答
//是楼层划分。它总是会给你结果的整数底。另一种是“常规”除法。
//是楼层划分。它总是会给你结果的底值。 另一个,/,是浮点除法。
下面是/和//之间的区别; 我在Python 3.7.2中运行了这些算术运算。
>>> print (11 / 3)
3.6666666666666665
>>> print (11 // 3)
3
>>> print (11.3 / 3)
3.7666666666666667
>>> print (11.3 // 3)
3.0
正如大家已经回答的,//是楼层划分。
这一点之所以重要,是因为//在2.2开始的所有Python版本中,包括Python 3,都是明确的层划分。x版本。
行为的改变取决于:
是否激活__future__导入(module-local) Python命令行选项,-Q old或-Q new
/→浮点除法
//→楼层划分
让我们看看Python 2.7和Python 3.5中的一些例子。
Python 2.7.10 vs. Python 3.5
print (2/3) ----> 0 Python 2.7
print (2/3) ----> 0.6666666666666666 Python 3.5
Python 2.7.10 vs. Python 3.5
print (4/2) ----> 2 Python 2.7
print (4/2) ----> 2.0 Python 3.5
现在,如果你想拥有(在Python 2.7中)与Python 3.5相同的输出,你可以执行以下操作:
Python 2.7.10
from __future__ import division
print (2/3) ----> 0.6666666666666666 # Python 2.7
print (4/2) ----> 2.0 # Python 2.7
然而在Python 2.7和Python 3.5中,层划分没有任何区别。
138.93//3 ---> 46.0 # Python 2.7
138.93//3 ---> 46.0 # Python 3.5
4//3 ---> 1 # Python 2.7
4//3 ---> 1 # Python 3.5
总结
x//y:精确的整数除法 int(x/y) OR math.floor(x/y):不精确的整数除法(但几乎正确) X /y:浮点除法(没有意义)
显著计算结果
import math
N = 1004291331219602346 # huge number
print(N//100) #=> 10042913312196023 is correct answer
print(math.floor(N/100)) #=> 10042913312196024 is wrong answer
print(math.ceil(N/100)) #=> 10042913312196024 is wrong answer
print(int(N/100)) #=> 10042913312196024 is wrong answer
考虑
考虑int(x/y)的取值。 首先,Python计算表达式x/y并得到不精确的浮点数z。 其次,Python计算表达式int(z)。 当意义的丧失不可忽视时,我们会得到错误的结果。