我想提高我的for循环的速度从非常大的文件中读取行。我有两个文件,我从第一个文件一行一行在for
环取信息,并通过if
声明符合这些每个从第二档线。由于这两个文件有上百万线的,这需要花费很长时间。
我在这里发布我的代码;我怎样才能提高循环语句来提高执行的速度?
#!/usr/bin/python
#open file1
f1 = open("../../Reapeat_analysis/FIMO/fimo_out/fimo.gff",'r')
#open file2
f2 = open("../BS_Forward.fastq_bismark_pe.CX_report.txt",'r')
f1.seek(0)
f2.seek(0)
#open and save output
fOut = open("output_sample_CG+.txt",'w')
#Reading file1 lines in for loop
for line1 in f1:
line1 = line1.split('\t')
s1 = int(line1[3])
s2 = int(line1[4])
s0 = str(line1[0])
count = 0
percent = 0
lt = []
#Reading file2 lines for each file1 line
for line2 in f2:
line2 = line2.split("\t")
#Matching desired condition
if (s0 == str(line2[0])) and (s1 <= int(line2[1]) <= s2) and (str(line2[5])=="CG") and (str(line2[2])=="+"):
lt.append(line2)
count = count + 1
#saving each matched conditions
fOut.write(str(s1) + "-" + str(s2) + ":" + str(s0) + "\t" + str(count) + "\t" + str(lt))
f2.seek(0)
fOut.close()
介于0和100行f2
文件的匹配滤波器(str(line2[5])=="CG") and (str(line2[2])=="+")
。
你有一个O(N * M)遍历文件I / O,这是非常缓慢的确实。您可以通过使用csv
模块做分析每一行成C代码对你的列表提高每行处理,并删除冗余str()
通话(你已经有一个字符串),但是你真正的问题是嵌套循环。
你可以很容易地避免这个循环。有可能是数以百万计在你的第二个文件中的行,但你已经过滤那些行要少很多,0到100,可以在内存中平凡举行,在旁边没有时间每s0
值之间的访问。
从存放在字典中的每一行的信息;预解析第二列的整数,并整排存储输出在lt
列表输出文件:
import csv
# dictionary mapping row[0] to a list of (int(row[1]), line) values
report_map = {}
with open("../BS_Forward.fastq_bismark_pe.CX_report.txt", 'r', newline='') as report:
reader = csv.reader(report, delimiter='\t')
for row in reader:
if row[2] != "+" or row[5] != "CG":
continue
key, value = row[0], int(row[1])
line = '\t'.join(row)
report_map.setdefault(key, []).append((value, line))
构建字典之后,你可以看一下比赛反对O(1)时间s0
,所以你遍历f1
是一个简单的循环与各行的廉价操作。当你发现在report_map
字典中的比赛,你只需要循环关联列表对row[1]
整数值筛选:
with open("../../Reapeat_analysis/FIMO/fimo_out/fimo.gff", 'r', newline='') as fimo, \
open("output_sample_CG+.txt", 'w', newline='') as fout:
reader = csv.reader(fimo, delimiter='\t')
writer = csv.writer(fout, delimeter='\t')
for row in reader:
s0 = row[0]
s1, s2 = map(int, row[3:5])
if s0 not in report_map:
continue
lt = [r for i, r in report_map[s0] if s1 <= i <= s2]
writer.writerow(["{}-{}:{}".format(s1, s2, s0), len(lt), str(lt)])
我强烈反对存储从BS_Forward.fastq_bismark_pe.CX_report.txt
文件中的整条生产线,肯定不是作为一个Python printable representation。我不知道你打算如何使用这些数据,但至少可以考虑使用JSON以连载的lt
列表为字符串表示。 JSON是由其他平台可读和更快的解析回一个合适的Python数据结构。