2013-07-08 58 views
2

在下面的代碼中,我想計算序列中G和C字符的百分比。在Python 3中,我正確地得到了0.5,但在Python 2上,我得到0。爲什麼結果不同?Python 3中的分區給出的結果與Python 2中的不同

def gc_content(base_seq): 
    """Return the percentage of G and C characters in base_seq""" 
    seq = base_seq.upper() 
    return (seq.count('G') + seq.count('C'))/len(seq) 

gc_content('attacgcg') 
+0

可能重複](http://stackoverflow.com/questions/2958684/python-division) – Bakuriu

回答

7

/是在Python 3不同的運營商;在Python 2 /改變時,應用到2個整數操作數的行爲,並返回地面劃分,而不是結果:

>>> 3/2 # two integer operands 
1 
>>> 3/2.0 # one operand is not an integer, float division is used 
1.5 

地址:

from __future__ import division 

你的代碼的頂部,使/使用浮動在Python 2,或使用//除法強制Python 3中使用整數除法:

>>> from __future__ import division 
>>> 3/2 # even when using integers, true division is used 
1.5 
>>> 3//2.0 # explicit floor division 
1.0 

使用任一這些TECHN的iques在Python 2.2或更新版本中工作。請參閱PEP 238瞭解爲什麼會發生變化的細節。

+0

這是一個「最佳實踐」或gnibbler的第一個解決方案「更好? – ghal

+0

這是最佳做法。解決方法是使用'float()'也可以,但它基本上是一種避免這個問題的手段。來自__future__ import division'是處理Python 3切換行爲的正確方法。 –

+0

使用ipython時可以使用'from __future__ import division'嗎? – ghal

1

對於Python2 /是整數除法時分子和分母都int,你需要確保強制浮點除法

如。

return (seq.count('G') + seq.count('C'))/float(len(seq)) 

或者,你可以把

from __future__ import division 

在文件的頂部

2

在python2.x /執行整數除法。

>>> 3/2 
1 

,從而獲得所需結果,您可以使用float()改變操作數爲浮點的任意一個:

>>> 3/2.  #3/2.0 
1.5 
>>> 3/float(2) 
1.5 

或使用division__future__

>>> from __future__ import division 
>>> 3/2 
1.5 
[Python的分工
相關問題