这里有两个函数可以完全相同,但是有谁知道为什么使用count()
方法的方法比另一个方法快得多? (我的意思是它的工作原理又是如何构建?)为什么count()方法比for循环python更快
如果可能的话,我想比一个更容易理解的答案怎么在这里找到:Algorithm used to implement the Python str.count function 或什么的源代码:https://hg.python.org/cpython/file/tip/Objects/stringlib/fastsearch.h
def scoring1(seq):
score = 0
for i in range(len(seq)):
if seq[i] == '0':
score += 1
return score
def scoring2(seq):
score = 0
score = seq.count('0')
return score
seq = 'AATTGGCCGGGGAG0CTTC0CTCC000TTTCCCCGGAAA'
# takes 1min15 when applied to 100 sequences larger than 100 000 characters
score1 = scoring1(seq)
# takes 10 sec when applied to 100 sequences larger than 100 000 characters
score2 = scoring2(seq)
非常感谢您的回复
简短的回答是因为一群非常聪明的人从python发布以来一直在优化内建'count()'功能 –
你试过这个电脑吗?我的显然是比你快100-200倍。另外,为什么unpythonic索引循环?你**试图让它变慢吗? –
[用于实现Python str.count函数的算法]的可能重复(http://stackoverflow.com/questions/16806972/algorithm-used-to-implement-the-python-str-count-function) –