Skip to main content
 首页 » 编程设计

python之迭代3个文件并在python中生成第三个文件的最佳方法

2025年04月02日8落叶无声

我有三个包含列表列表的 txt 文件。

文件 1(9700 行):

ID1, data 1 

文件 2(210 万行):

ID1, ID2 

文件 3(1100 行):

ID2, data 3 

我想制作一个文件 4

  • 获取文件 1 中的所有行(ID1 和数据 1)
  • 获取 ID1 行的 ID2。
  • 获取该 ID2 的数据 3。
  • 保存文件ID1,数据1,ID2,文件4中文件1中所有行的数据3

我已经用 python 为它编写了一个脚本,但是 ATM 需要 1 小时。

这是它的作用:

file1 = [] 
file4 = [] 
file3 = [] 
 
final_list.append("ID1, ID2, DATA1, DATA2") 
 
#Import file1 
with open('file1.txt') as inputfile: #file 1: around 9.7k 
    for line in inputfile: 
        temp = line.strip().split(' ') 
        file1.append(temp) 
 
#Import file3 
with open('file3.txt') as inputfile: #file 3: around 1.1k 
    for line in inputfile: 
        temp = line.strip().split(' ') 
        file3.append(temp) 
 
print len(file1) 
 
#Iterate through file2 (so I only iterate once through this) 
with open('file2.txt') as inputfile: #File 2: 2.1 million 
    for line in inputfile: 
        temp = line.strip().split(' ') 
        for sublist in file1: #Only if first element is also in list 1 
            if sublist[0] == temp[0]: 
                for sublist2 in file3: 
                    if sublist2[0] == temp[1]: 
                        file4.append([temp, sublist[1], sublist2[1]]) 
 
print len(file4) 
 
print file4[:10] 
 
thefile = open('final.txt', 'w') 
for item in file4: 
  thefile.write("%s\n" % item) 
thefile.close() 

如前所述,ATM 取款需要一个小时。我怎样才能提高性能?我有很多循环,正在考虑是否可以通过某种方式更快地完成...

注意:ID只出现一次,数据可以是重复值

请您参考如下方法:

由于您的 ID 是唯一的,在您编写时,您可以使用字典而不是文件 1 和文件 3 的列表。因此,您的循环检查以查看 ID 是否存在减少为在这些字典的键集中进行一次查找。我不知道你的原始列表,但我认为字典对你的目的来说更快。因此,您可以在长文件上保存两次循环迭代。不过,将花费一些时间来组装 key 列表。请尝试以下方法:

file1 = {}                              # empty new dictionary 
file4 = [] 
file3 = {} 
 
final_list.append("ID1, ID2, DATA1, DATA2") 
 
#Import file1 
with open('file1.txt') as inputfile:    #file 1: around 9.7k 
    for line in inputfile: 
        temp = line.strip().split(' ') 
        file1[temp[0]] = temp[1]        # store ID1 and associated data in dict 
 
#Import file3 
with open('file3.txt') as inputfile:    #file 3: around 1.1k 
    for line in inputfile: 
        temp = line.strip().split(' ') 
        file3[temp[0]] = temp[1]        # store ID2 and associated data in dict 
 
print len(file1) 
 
#Iterate through file2 (so I only iterate once through this) 
keys1 = file1.keys()                    # for fast lookup, precalculate the list of ID1 entries 
keys3 = file3.keys()                    # for fast lookup, precalculate the list of ID2 entries 
with open('file2.txt') as inputfile:    #File 2: 2.1 million 
    for line in inputfile: 
        temp = line.strip().split(' ') 
        if temp[0] in keys1: 
            if temp[1] in keys3: 
                file4.append([temp, file1[temp[0]], file3[temp[0]]]) 
 
print len(file4) 
 
print file4[:10] 
 
thefile = open('final.txt', 'w') 
for item in file4: 
  thefile.write("%s\n" % item) 
thefile.close() 

问候,