Skip to main content
 首页 » 编程设计

python之列出两个文件之间比较慢的代码

2024年10月01日9飞鱼

例如我有两个文件:

文件1:

id chrom start     end       strand 
g1  11  98566330    98566433    - 
g2  11  98566295    98566433    - 
g3  11  98566581    98566836    - 

文件2

id chrom   start   end      strand  gene_id            gene_name somecol1...somecol10 
g1  11  98566330    98566433    -   ENSMUSG00000017210  Med24 
g2  11  98566295    98566433    -   ENSMUSG00000017210  Med24 
g3  11  98566581    98566836    -   ENSMUSG00000017210  Med24 

期望的输出

id chrom start     end       strand gene_id gene_namesomecol1...somecol10 
g1 11  98566330    98566433    -   ENSMUSG00000017210 Med24 
g2 11  98566295    98566433    -   ENSMUSG00000017210 Med24 
g3 11  98566581    98566836    -   ENSMUSG00000017210 Med24 

我基本上想做的是从两个文件中获取匹配的 id 列,如果匹配,则在新文件中打印/写入 file1 和 file2 中的一些列(我当前的代码)

with open('~/outfile.txt', 'w') as w: 
     for id1 in c1: #c1 is list where i append each line from file1 
         for id2 in d1: #d2 is list where i append each line from file2 
             if id1[0] in id2[0]: #is this condition faster (condition1) 
         #   if id1[0] == id2[0]:#or this condition is faster (condition2) 
                out = ('\t'.join(id2[0:6]),id1[1],id1[2],id2[9],id2[10]) 
                w.write('\t'.join(out) + '\n') 

问题是这段代码在 condition2 下可以正常工作,但速度很慢可能是因为我试图匹配列表 c1 之间的每一行 id1[0] == id2[0]和 d1 也因为 file2 有大约 500000 行。

目前我只能想出两个我正在尝试学习的条件,这可能会使代码更快

是否有更好的逻辑可以提高速度。

编辑:

我需要将文件 col0 (id) 与 file2 col(id) 匹配,如果为真,则切片 col0:6 中的元素、file1 中的 col[1,2] 和 file2 中的 col9,10

期望的输出

id(file2) chrom(file2) start(file2)     end(file2)       strand(file2) gene_id(file2) gene_name(file2)somecol1(file1)...somecol10(file1) 
g1 11  98566330    98566433    -   ENSMUSG00000017210 Med24 
g2 11  98566295    98566433    -   ENSMUSG00000017210 Med24 
g3 11  98566581    98566836    -   ENSMUSG00000017210 Med24 

请您参考如下方法:

如果我理解正确,只有当 id 字段在第一个文件中时,您才想保留第二个文件中的行。

我会一直使用csv模块,这样更干净。

首先,我会构建一组 id 字段,以便从文件 1 的内容(每行只有 5 个字段的那个)中快速查找

然后我会读取第二个文件,并且仅当行 id 包含在集合中时才将行写入第三个文件。您将受益于 set 查找的速度:

import csv 
 
with open("file1.txt") as file1: 
    cr = csv.reader(file1,delimiter="\t") 
    next(cr)  # skip title 
    subset = {row[0] for row in cr} # build lookup set in a set comprehension for ids 
 
with open("file2.txt") as file2, open("result.txt","w",newline="") as file3:  # python 2: open("result.txt","wb") 
    cr = csv.reader(file2,delimiter="\t") 
    cw = csv.writer(file3,delimiter="\t") 
    cw.writerow(next(cr))  # write title 
    cw.writerows(row for row in cr if row[0] in subset)