提高python脚本的速度

The*_*man 5 python

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

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

从这些行中的每一行开始,我从第一个和最后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()
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 6

尝试定义lineCharsListset而不是列表:

lineCharsList = set()
...
lineCharsList.add(lineChars)
Run Code Online (Sandbox Code Playgroud)

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


DTi*_*ing 5

您可以使用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))
Run Code Online (Sandbox Code Playgroud)