提高嵌套循环的速度

2024-09-30 10:36:52 发布

您现在位置: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, 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]   

Tags: 代码inforlenifcountrange速度
1条回答
网友
1楼 · 发布于 2024-09-30 10:36:52

如果使用python3,则将izip替换为zip,将{}替换为range。在

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, 1, 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。我删除了它们,因为它们看起来已经是intNum_mismatcheslk)。在

相关问题 更多 >

    热门问题