Skip to main content
 首页 » 编程设计

python之两组数据的匹配指标

2025年05月04日6findumars

我有一个标题为 A B C D 的表格。D 下的值由 A、B、C 下的值索引。

我还有一个对象列表,这些对象由 A 和 B 列中包含的值索引,即 (A,B)。

对于每个对象,我想将表中与我的对象具有相同 A、B 索引的所有条目写入文件。

这就是我正在做的:

prescriptions = {} 
 
#Open ABCD table and create a dictionary mapping A,B,C to D 
with open(table_file) as table: 
    reader = csv.reader(table, delimiter = '\t') 
    for row in reader: 
        code = (row[0], row[1], row[2]) 
        prescriptions[code]=row[3] 
 
for x in objects: 
    x_code = (x.A, x.B) 
 
    for p in prescriptions: 
        #check to see if A,B indices on x match those of the table entry 
        if p[0:2] == x_code: 
            row = prescriptions[p] 
            line = ",".join(p) +"," + row +"\n" 
            output.write(line) 

这行得通。我得到了我想要的确切输出;然而,当表格和列表变大时,会花费大量时间。

我想修改我的迭代器(当我找到一个匹配项时删除 p),but I know not to do that .

我能做些什么来加快速度吗?

请您参考如下方法:

我猜 prescription 是一本字典?

为什么不用字典 prescription2 以 A、B 作为键、C、D 的列表作为值?这将使您免于遍历所有字典的麻烦。

prescriptions = {} 
prescriptions2 = {} 
 
#Open ABCD table and create a dictionary mapping A,B,C to D 
with open(table_file) as table: 
    reader = csv.reader(table, delimiter = '\t') 
    for row in reader: 
        code = (row[0], row[1], row[2]) 
        prescriptions[code]=row[3] 
        key = (row[0],row[1]) 
        if not key in prescription2: 
            prescription2[key] = [] 
        value = (row[2],row[3]) 
        prescription2[key].append(value) 
 
for x in objects: 
    x_code = (x.A, x.B) 
    if x_code in prescription2: 
        for item in prescription2[x_code]: 
            line = ",".join(x_code+item)+"\n" 
            output.write(line)