Python 中的两个正斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14444520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two forward slashes in Python
提问by Biff
I came across this sample of code from a radix sort:
我从基数排序中遇到了这个代码示例:
def getDigit(num, base, digit_num):
# pulls the selected digit
return (num // base ** digit_num) % base
What does the //do in Python?
什么是//Python中吗?
采纳答案by sepp2k
//is the floor division operator. It produces the floor of the quotient of its operands, without floating-point rounding for integer operands. This is also sometimes referred to as integer division, even though you can use it with floats, because dividing integers with /used to do this by default.
//是楼层划分算子。它产生其操作数的商的下限,而不对整数操作数进行浮点舍入。这有时也称为整数除法,即使您可以将它与浮点数一起/使用,因为默认情况下使用整数除法来执行此操作。
In Python 3, the ordinary /division operator returns floating point values even if both operands are integers, so a different operator is needed for floor division. This is different from Python 2 where /performed floor division if both operands were integers and floating point division if at least one of the operands was a floating point value.
在 Python 3 中,/即使两个操作数都是整数,普通的除法运算符也会返回浮点值,因此需要不同的运算符进行地板除法。这与 Python 2 不同,在 Python 2 中,/如果两个操作数都是整数,则执行地板除法,如果至少一个操作数是浮点值,则执行浮点除法。
The //operator was first introduced for forward-compatibility in Python 2.2 when it was decided that Python 3 should have this new ability. Together with the ability to enable the Python 3 behavior via from __future__ import division(also introduced in Python 2.2), this enables you to write Python 3-compatible code in Python 2.
//当决定 Python 3 应该具有这种新功能时,该运算符首先在 Python 2.2 中引入以实现向前兼容性。连同通过from __future__ import division(也在 Python 2.2 中引入)启用 Python 3 行为的能力,这使您能够在 Python 2 中编写与 Python 3 兼容的代码。
回答by LWZ
You can just try it:
你可以试试看:
In []: 5/2
Out[]: 2
In []: 5.0/2
Out[]: 2.5
In []: 5.0//2
Out[]: 2.0
This should be self-explanatory.
这应该是不言自明的。
(This is in Python 2.7.)
(这是在 Python 2.7 中。)

