//在python中做什么?

时间:2013-02-11 20:18:14

标签: python

我正在阅读http://learnpythonthehardway.org/book/ex37.html,但我不明白//=符号的作用。 /=对我有意义:

a = 9
a /= 3
a == 3 # => True

但是//=

a = 9
a //= 3
a == 3 # => Also True

感谢。

3 个答案:

答案 0 :(得分:3)

//在python3中作为“整数除法”,看看this answer

在C中,整数上/的除法作为“与地板划分”或“整数除法”。为了提供这种功能,python提供了//运算符,与/不同,它将提供浮点结果。

权威参考肯定是pep-238

从命令行版本(当你试图弄清楚这样的事情时很有用):

Python 3.2.3 (default, Apr 11 2012, ...
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 10
>>> a/3
3.3333333333333335
>>> a//3
3
>>>

答案 1 :(得分:3)

/如您所知经典分部。在Python 2.2中添加了//运算符,它执行 floor division ,并且通过添加此运算符,您可以使用from __future__ import division使/运算符执行{{1分裂。

true相当于a //= 3

所以,这是摘要:

a = a // 3

答案 2 :(得分:0)

//是分区:它分割并向下舍入,但如果操作数是浮点数,它仍然会产生一个浮点数。在Python 2中,它与整数的常规除法相同,除非您使用from __future__ import division来获得Python 3的“真正”除法行为。

所以,是的,这有点复杂。本质上,通过划分两个整数来重新创建Python 2中的行为,因为Python 3中的更改。

在Python 2中:

  • 11 / 52
  • 11.0 / 5.02.2
  • 11 // 52
  • 11.0 // 5.02.0

在Python 3中, Python 2与from __future__ import division Python 2与-Q new一起运行:

  • 11 / 52.2
  • 11.0 / 5.02.2
  • 11 // 52
  • 11.0 // 5.02.0

当然,添加=只会将其转换为像/=这样的组合赋值运算符。