使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:
>>> 6/3
2
>>> 6//3
2
当前回答
Python 3
操作 结果 笔记 X / y x和y的商 X // y x和y的底商 (1) 注: 也称为整数除法。结果值是一个整型,尽管结果的类型不一定是int。结果总是趋近于负无穷:1//2等于0,(-1)//2等于-1,1//(-2)等于-1,(-1)//(-2)等于0。
Python 2
Operation Result Notes x / y quotient of x and y (1) x // y (floored) quotient of x and y (4)(5) Notes: 1. For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value. 4. Deprecated since version 2.3: The floor division operator, the modulo operator, and the divmod() function are no longer defined for complex numbers. Instead, convert to a floating point number using the abs() function if appropriate. 5. Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.
其他回答
正如大家已经回答的,//是楼层划分。
这一点之所以重要,是因为//在2.2开始的所有Python版本中,包括Python 3,都是明确的层划分。x版本。
行为的改变取决于:
是否激活__future__导入(module-local) Python命令行选项,-Q old或-Q new
Python 3
操作 结果 笔记 X / y x和y的商 X // y x和y的底商 (1) 注: 也称为整数除法。结果值是一个整型,尽管结果的类型不一定是int。结果总是趋近于负无穷:1//2等于0,(-1)//2等于-1,1//(-2)等于-1,(-1)//(-2)等于0。
Python 2
Operation Result Notes x / y quotient of x and y (1) x // y (floored) quotient of x and y (4)(5) Notes: 1. For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value. 4. Deprecated since version 2.3: The floor division operator, the modulo operator, and the divmod() function are no longer defined for complex numbers. Instead, convert to a floating point number using the abs() function if appropriate. 5. Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.
//是楼层划分。它总是会给你结果的底值。 另一个,/,是浮点除法。
下面是/和//之间的区别; 我在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
Python 2.7和其他即将推出的Python版本:
部门(/)
左手操作数除以右手操作数
例如:4 / 2 = 2
楼层划分(//)
操作数的除法,其结果为除小数点后数的商。但如果其中一个操作数是负的,结果会被取整,即从零四舍五入(直到负无穷):
例子:9 / / 2 = 4和9.0 / / 2.0 = 4.0,-11 / / 3 = 4,-11.0 / / 3 = -4.0
/事业部和//楼层事业部操作符都以类似的方式操作。
//是楼层划分。它总是会给你结果的整数底。另一种是“常规”除法。