我有两个文件:
文件1:
CL1 AA XX YY ZZ SS \n
CL2 3_b AA
文件2:
AA string1
AA string2
3_b string3
我的预期输出是:
CL1 AA string1
CL1 AA string2
CL2 3_b string3
CL2 AA string1
CL2 AA string2
为此我编写了以下代码:
import numpy as np
print("Reading Files...")
header = open('File1', 'r')
cl = header.readlines()
infile = np.genfromtxt('File2', dtype='str', skip_header=1)
new_array = []
for j in range(len(infile)):
for row in cl:
element = row.split("\t")
ele_size = len(element)
for i in range(0, ele_size):
if np.core.defchararray.equal(infile[j,0], element[i]):
clust = element[0]
match1 = infile[j,0]
match2 = infile[j,1]
combo = "\t".join([clust, match1, match2])
new_array.append(combo)
np.savetxt('output.txt',new_array, fmt='%s', delimiter='\t')
这会生成我想要的输出。但由于 file2 中有大约 700000 行和大约 65000 个簇,因此迭代需要大量时间。谁能建议一种有效的方法来解析它?
是否可以将第一个文件保留为列表,将第二个文件保留为字典?然后迭代关键值?
最佳答案
您应该为 File2 存储一个字典,然后当您迭代 File1 中的行时,您可以在 File2 字典中查找键。这意味着单级 for
循环而不是三级 for
循环。
我认为 NumPy 不会帮助你解决这些问题——更容易忽略它并只编写常规的 Python。我认为最终会很快。
关于python - 在字典上迭代列表以映射项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34418644/