2013-02-11 39 views

回答

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 
>>> 
3

/你知道不經典師//運營商是在Python 2.2中添加的,其中地板分區,並且加上此運營商,您可以使用from __future__ import division使/運營商做true劃分。

a //= 3相當於a = a // 3

所以,這裏的總結:

Python Version  operator/  operator // 
------------------------------------------------- 
2.1x and older  classic   Not Added 

2.2 and newer   classic   floor 
(without import)  

2.2 and newer   true    floor 
(with import) 
+0

如果定義了該方法(參見http://docs.python.org/2/reference/datamodel.html#object.__ifloordiv__),則相當於'a = a .__ ifloordiv __(3)'。我*想*某些類型(也許NumPy數組?)重寫該操作符就地行事。儘管如此,它並不重要。 – delnan 2013-02-11 20:22:05

+0

@delnan - 對於可變的類型,api希望它可以在適當的位置運行,儘管它實際上並不需要。 – mgilson 2013-02-11 20:25:11

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

而且,當然,添加=只是將它變成一個組合賦值運算符,如/=