python3中的除法与python2中的除法结果不同

2024-04-24 04:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我想计算序列中G和C字符的百分比。在python3中,我正确地得到0.5,但在python2上,我得到0。为什么结果不同?在

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')

Tags: the代码basereturndefcount序列content
3条回答

在python2.x中,/执行整数除法。在

>>> 3/2
1

要获得所需的结果,可以使用float()将其中一个操作数更改为浮点:

^{pr2}$

或从__future__使用division

>>> from __future__ import division
>>> 3/2
1.5

/是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

添加:

^{pr2}$

要使/在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

在Python2.2或更高版本中使用这两种技术都可以。请参见PEP 238以了解更改原因的基本细节。在

对于Python2/是整数除法,而分子和分母都是int,您需要确保强制浮点除法

例如

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

或者,您可以

^{pr2}$

在文件的顶端

相关问题 更多 >