【发布时间】:2015-09-27 04:57:48
【问题描述】:
我有一个包含字符串列表的输入文件。
我从第二行开始每隔四行迭代一次。
从每一行中,我从第一个和最后 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 变大,脚本会变得很慢。我没有任何建议,但这很可能是问题所在。
-
我也是这么想的。 RAM 应该不是问题,因为我正在开发一个有足够余量的计算集群。但我不确定是否有比将所有内容存储在这样的列表中更好的方法。
-
顺便说一句,您可以在
with语句中包含输出文件 -with open(input_file, 'r') as f, open(output_file, 'w') as target:。 -
你用的是什么 Python 版本?
标签: python