简体   繁体   English

使用另一个列表的元素过滤列表 - Python

[英]Filtering lists with elements of another list - Python

so I have two files, one containing barcodes and the other containing what I want to search.所以我有两个文件,一个包含条形码,另一个包含我想要搜索的内容。 File 1 is in the format:文件 1 的格式为:

BC01 123 BC01 123

BC02 124 BC02 124

BC03 125 BC03 125

my second file is in the format:我的第二个文件的格式是:

INV01 123axxxx INV01 123axxxx

INV02 123bxxxx INV02 123bxxxx

INV03 124cxxxx INV03 124cxxxx

INV04 125dxxxx INV04 125dxxxx

Both files are tab delimited between the "tag" and the rest of the line.这两个文件都在“标签”和该行的其余部分之间用制表符分隔。

So what Im currently trying to do is to search the second file with the barcodes found in the first and output them to separate files.因此,我目前尝试做的是使用在第一个文件中找到的条形码搜索第二个文件,并将它们输出到单独的文件中。

So the end result that I want are 3 separate files BC01, BC02, BC03 with the corresponding inventory numbers with the barcode cut off, for example:所以我想要的最终结果是 3 个单独的文件 BC01, BC02, BC03 以及相应的库存编号,条形码被切断,例如:

file BC01 would read:文件 BC01 将显示:

INV01 INV01

axxxx axxxx

INV02 INV02

bxxxx xxx

What I have right now are lists of the separate tab delimited portions of both files: BCID, BCnumber, INVID, and INVnumber and I'm not quite sure how to proceed from here.我现在拥有的是两个文件的单独制表符分隔部分的列表:BCID、BCnumber、INVID 和 INVnumber,我不太确定如何从这里开始。

Create a dictionary out of file_1:从 file_1 创建字典:

barcodes = {}
with open(file_1) as file_one:
    csv_reader = csv.reader(file_one, delimiter='\t')
    for row in csv_reader:
        barcodes[row[1]] = row[0]
file_one.close()

Use this to search in second file and build a output map:使用它在第二个文件中搜索并构建输出映射:

output = defaultdict(list)
with open(file_2) as file_two:
    csv_reader = csv.reader(file_two, delimiter='\t')
    for row in csv_reader:
        key = row[1][:2]
        output[barcodes[key]].append(row[0])
        output[barcodes[key]].append(row[1][2:])
file_two.close()

The output dictionary would then be: output字典将是:

{
'BC01':['INV01', 'axxxx', 'INV02', 'bxxxx']
'BC02':['INV03', 'cxxxx']
'BC03':['INV04', 'dxxxx']
}

Now iterate through this dictionary, create files with the names of the keys and write out the contents of the file with the corresponding values.现在遍历这个字典,用键名创建文件,并用相应的值写出文件的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM