我写了一个剧本,但速度慢得令人望而却步。我想知道是否有人能建议如何加快速度。我认为剧本太慢的部分是这样的:
[2314,2395,10672,8683,5075]
对于ListOfHumanGenes中的每个基因:如果有基因名称,打开标记为".HumanHomologs“的100个文件: NumberOfTrials +=1,如果print < 0:如果”年龄“列< 0: UnderexpressedSuccess +=1 elif "Age”列>0: OverexpressedSuccess +=1打印each_gene +“+ NumberOfTrials +“t”UnderexpressedSuccess打印each_gene +“t”+ NumberOfTrials +“t”OverexpressedSuccess
本节的代码是:
for each_item in ListOfHumanGenes:
OverexpressedSuccess = 0
UnderexpressedSuccess = 0
NumberOfTrials = 0
for each_file in glob.glob("*.HumanHomologs"):
open_each_file = open(each_file).readlines()[1:]
for line in open_each_file:
line = line.strip().split()
if each_item == line[0]:
NumberOfTrials +=1 #i.e if the gene is in the file, NumberOfTrials +=1. Not every gene is guaranteed to be in every file
if line[-1] != "NA":
if float(line[-1]) < float(0.05):
if float(line[-2]) < float(0):
UnderexpressedSuccess +=1
elif float(line[-2]) > float(0):
OverexpressedSuccess +=1
underexpr_output_file.write(each_item + "\t" + str(UnderexpressedSuccess) + "\t" + str(NumberOfTrials) + "\t" + str(UnderProbability) +"\n") #Note: the "Underprobabilty" float is obtained earlier in the script
overexpr_output_file.write(each_item + "\t" + str(OverexpressedSuccess) + "\t" + str(NumberOfTrials) + "\t" + str(OverProbability) +"\n") #Note: the "Overprobability" float is obtained earlier in the script
overexpr_output_file.close()
underexpr_output_file.close()
这将产生两个输出文件(一个用于over,另一个用于欠表达),如下所示;这些列是GeneName、#过表达/#欠表达、#NumberTrials,然后可以忽略最后一列:
2314 8 100 0.100381689982
2395 14 90 0.100381689982
10672 10 90 0.100381689982
8683 8 98 0.100381689982
5075 5 88 0.100381689982
每个".HumanHomologs“文件中都有>8,000行,其中的基因列表大约有20,000个基因。所以我知道这很慢,因为在这2万种基因中,每种基因都会打开100个文件,并在每个文件中找到8000条以上的基因。我想知道是否有人可以建议我可以做的编辑,使这个脚本更快/更有效率?
发布于 2017-01-11 10:58:57
您的算法将打开所有这100个文件1000次。立即想到的优化是将文件作为最外层的循环进行迭代,这将确保每个文件只打开一次。然后检查每个基因的存在,并记录你想要的任何其他记录。
此外,熊猫模块将非常方便地处理这种类型的csv文件。检查一下熊猫
发布于 2017-01-11 11:59:07
谢谢你的帮助;交换循环的洞察力是非常宝贵的。改进后的、效率要高得多的脚本如下所示(注意:我现在有了一个ListOfHumanGenes (如上面所述),我现在有一个DictOfHumanGenes,其中每个键都是人类基因,值是(1) NumberOfTrials、(2) UnderexpressedSuccess和(3) OverexpressedSuccess的列表;这也加快了代码的其他部分):
for each_file in glob.glob("*.HumanHomologs"):
open_each_file = open(each_file).readlines()[1:]
for line in open_each_file:
line = line.strip().split()
if line[0] in DictOfHumanGenes:
DictOfHumanGenes[line[0]][0] +=1 #This is the Number of trials
if line[-1] != "NA":
if float(line[-1]) < float(0.05):
if float(line[-2]) < float(0):
DictOfHumanGenes[line[0]][1] +=1 #This is the UnexpressedSuccess
elif float(line[-2]) > float(0):
DictOfHumanGenes[line[0]][2] +=1 #This is the OverexpressedSuccess
我现在正在调查熊猫,看看如何把它融入其中,如果我能让熊猫的代码更高效的话,我会在这里发布答案。
https://stackoverflow.com/questions/41588261
复制相似问题