繁体   English   中英

提高python脚本的速度

[英]Improving the speed of a python script

我有一个包含字符串列表的输入文件。

我从第二行开始迭代每四行。

从这些行中的每一行开始,我从第一个和最后6个字符创建一个新字符串,并且仅当新字符串是唯一的时才将其放在输出文件中。

我写的代码可以实现这一点,但是我正在使用非常大的深度排序文件,并且已经运行了一天并且没有取得多大进展。 所以我正在寻找任何建议,如果可能的话,这样做会更快。 谢谢。

def method():
    target = open(output_file, 'w')

    with open(input_file, 'r') as f:
        lineCharsList = []

        for line in f:
            #Make string from first and last 6 characters of a line
            lineChars = line[0:6]+line[145:151] 

            if not (lineChars in lineCharsList):
                lineCharsList.append(lineChars)

                target.write(lineChars + '\n') #If string is unique, write to output file

            for skip in range(3): #Used to step through four lines at a time
                try:
                    check = line    #Check for additional lines in file
                    next(f)
                except StopIteration:
                    break
    target.close()

尝试将lineCharsList定义为set而不是列表:

lineCharsList = set()
...
lineCharsList.add(lineChars)

这将提高性能in运营商。 此外,如果内存根本不是问题,您可能希望在列表中累积所有输出并在结尾处全部写入,而不是执行多个write()操作。

您可以使用https://docs.python.org/2/library/itertools.html#itertools.islice

import itertools

def method():
    with open(input_file, 'r') as inf, open(output_file, 'w') as ouf:
        seen = set()
        for line in itertools.islice(inf, None, None, 4):
            s = line[:6]+line[-6:]
            if s not in seen:
                seen.add(s)
                ouf.write("{}\n".format(s))

除了使用set as Oscar建议之外,你还可以使用islice跳过行而不是使用for循环。

正如指出这个帖子 ,islice预处理C中的迭代器,所以它应该是比使用一个普通的Python for循环快得多。

尝试更换

lineChars = line[0:6]+line[145:151]

lineChars = ''.join([line[0:6], line[145:151]])

因为它可以更有效,取决于具体情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM