在Python中使用'//'的原因是什么? [英] What is the reason for having '//' in Python?
问题描述
我在某人的代码中看到了这一点:
I saw this in someone's code:
y = img_index // num_images
其中 img_index
是运行索引,而 num_images
是3。
where img_index
is a running index and num_images
is 3.
当我在IPython中碰到 //
时,它的作用就像是分隔符(即一个正斜杠)。我只是想知道是否有理由使用双正斜杠?
When I mess around with //
in IPython, it seems to act just like a division sign (i.e. one forward slash). I was just wondering if there is any reason for having double forward slashes?
推荐答案
在Python 3中,他们将 /
运算符进行浮点除法,并添加了 //
运算符以进行整数除法(即无余数的商);而在Python 2中, /
运算符只是整数除法,除非其中一个操作数已经是浮点数。
In Python 3, they made the /
operator do a floating-point division, and added the //
operator to do integer division (i.e. quotient without remainder); whereas in Python 2, the /
operator was simply integer division, unless one of the operands was already a floating point number.
在Python 2.X中:
In Python 2.X:
>>> 10/3
3
>>> # to get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335
在Python 3中:
In Python 3:
>>> 10/3
3.3333333333333335
>>> 10//3
3
有关更多参考,请参见 PEP238 。
For further reference, see PEP238.
这篇关于在Python中使用'//'的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!