使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
当前回答
总结
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)。 当意义的丧失不可忽视时,我们会得到错误的结果。
其他回答
正如大家已经回答的,//是楼层划分。
这一点之所以重要,是因为//在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
5.0//2的结果是2.0,而不是2,因为//操作符返回值的返回类型遵循Python强制转换(类型强制转换)规则。
Python促进低数据类型(整数)到高数据类型(浮点数)的转换,以避免数据丢失。
//是楼层划分。它总是会给你结果的整数底。另一种是“常规”除法。
前面的答案都很好。我想再补充一点。在某些情况下,它们会得到相同的商。之后,除法运算符(//)可以正常工作,但除法(/)运算符不行:
>>> int(755349677599789174 / 2) # Wrong answer
377674838799894592
>>> 755349677599789174 // 2 # Correct answer
377674838799894587