在Python中使用'//'的原因是什么?

编程入门 行业动态 更新时间:2024-10-26 20:30:27
本文介绍了在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中使用'//'的原因是什么?

本文发布于:2023-11-26 03:23:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632439.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原因   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!