Python 3 中的除法结果与 Python 2 中的不同 [英] Division in Python 3 gives different result than in Python 2
问题描述
在下面的代码中,我想计算序列中 G 和 C 字符的百分比.在 Python 3 中我正确得到 0.5
,但在 Python 2 中我得到 0
.为什么结果不同?
def gc_content(base_seq):"""返回base_seq中G和C字符的百分比"""seq = base_seq.upper()返回 (seq.count('G') + seq.count('C'))/len(seq)gc_content('attacgcg')
/
是 Python 3 中的不同运算符;在 Python 2 中,/
在应用于 2 个整数操作数时会改变行为并返回地板除法的结果:
添加:
from __future__ 导入师
到你的代码顶部让 /
在 Python 2 中使用浮点除法,或者使用 //
强制 Python 3 使用整数除法:
在 Python 2.2 或更新版本中使用这两种技术中的任何一种都有效.请参阅 PEP 238 了解更改原因的具体细节.
In the following code, I want to calculate the percent of G and C characters in a sequence. In Python 3 I correctly get 0.5
, but on Python 2 I get 0
. Why are the results different?
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')
/
is a different operator in Python 3; in Python 2 /
alters behaviour when applied to 2 integer operands and returns the result of a floor-division instead:
>>> 3/2 # two integer operands
1
>>> 3/2.0 # one operand is not an integer, float division is used
1.5
Add:
from __future__ import division
to the top of your code to make /
use float division in Python 2, or use //
to force Python 3 to use integer division:
>>> from __future__ import division
>>> 3/2 # even when using integers, true division is used
1.5
>>> 3//2.0 # explicit floor division
1.0
Using either of these techniques works in Python 2.2 or newer. See PEP 238 for the nitty-gritty details of why this was changed.
这篇关于Python 3 中的除法结果与 Python 2 中的不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!