python – 提高嵌套循环的速度
发布时间:2020-12-20 13:49:17 所属栏目:Python 来源:网络整理
导读:我试图提高我的 python代码的速度.执行大型数据集需要很长时间.有更好的方法以更快的速度完成吗? for i in range(0,len(nodes)):fragment = nodes[i]for l in range(0,length1): fragment1 = Text[l:int(l)+int(k)] count = [0]*gen_len for j in range( 0,
|
我试图提高我的
python代码的速度.执行大型数据集需要很长时间.有更好的方法以更快的速度完成吗?
for i in range(0,len(nodes)):
fragment = nodes[i]
for l in range(0,length1):
fragment1 = Text[l:int(l)+int(k)]
count = [0]*gen_len
for j in range( 0,gen_len ):
if fragment[j] != fragment1[j]:
count[j] = count[j]+1
if j == (gen_len-1):
if int(sum(count)) <= int(Num_mismatches):
count2[i] = count2[i]+1
result2[i] = fragment
result.append(fragment)
if count2[i] > maxval:
maxval = count2[i]
解决方法
如果使用Python 3将zip替换为izip,使用范围替换xrange.
from itertools import islice,izip
for i in xrange(0,len(nodes)):
fragment = nodes[i]
for l in xrange(0,length1):
# fragment1 was replaced by islice to avoid list creation
# It may or may not be faster. Try timing a version
# where you replace islice(Text,1,l+k) with Text[l:int(l)+int(k)]
count = sum(f != f1 for f,f1 in izip(fragement,islice(Text,l+k)))
if count <= Num_mismatches:
count2[i] += 1
# code smell: why have both result and result2?
result2[i] = fragment
result.append(fragment)
# you are not using maxval anywhere in these loops.
# you may want to set it after these loops.
if count2[i] > maxval:
maxval = count2[i]
有很多地方你要投入到int.我删除了那些因为看起来它们已经是int(Num_mismatches,l,k). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
