python - 在字典上迭代列表以映射项目

标签 python numpy dictionary python-itertools

我有两个文件:

文件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/

相关文章:

Python:根据一个列表的索引对字典列表进行排序

python - 如何使用 python pandas 从 dict 类型数据框中删除重复项?

python - 如何从子字符串中获取列表中的索引值?

python - 需要 NumPy ndarray 数据的缓冲区类

numpy - 色相饱和度直方图

javascript - 使用 React js 为每一行创建动态复选框

python - python-3.3 的模拟工具

Python valueError 使用 hstack() (ValueError : all the input array dimensions except for the concatenation axis must match exactly)

python - 模型的特征数量必须与输入匹配?

c# - 哈希表到 Dictionary<> syncroot 。