首页 > 解决方案 > 如何将列表中的匹配元素附加到另一个列表?

问题描述

我有两个清单: file_name = ['AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg', 'AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg', 'CJ19+244082+ Primary.jpg']

number = ['775002', '200998', '244082']

我正在尝试将number我在列表中找到的匹配字符串附加到列表中file_name,使其变为:

number = [['775002', 'AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg'], ['200998', 'AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg'], ['244082', 'CJ19+244082+ Primary.jpg']]

这些列表是从单列 .csv 文件中提取的,因此我还希望以 Excel 上可读的格式将其导出以在数据库中工作。

这是我到目前为止所拥有的:


with open('file_name.csv', newline='') as csvfile:
    file_name = list(csv.reader(csvfile))

with open('number.csv', newline='') as csvfile:
    number = list(csv.reader(csvfile))

for i in number:
    matching = [s for s in file_name if number[i] in s]
    number[i].append(matching)```

标签: python

解决方案


您可以将所有内容存储在dict

with open('file_name.csv', newline='') as csvfile:
   file_names = [line.split()[0] for line in csvfile]

with open('number.csv', newline='') as csvfile:
   numbers = [line.split()[0] for line in csvfile]

newdict = {}

for file_name in file_names:
    for number in numbers:
        if not number in newdict:
            newdict[number] = []
        if number in file_name:
            newdict[number].append(file_name)

输出:

{'775002': ['AC30+775002+ secondary 2.jpg', 'AC30+775002+primary.jpg'], '200998': ['AX-5+200998+primary.jpg', 'AX-5+200998+secondary 2.jpg'], '244082': ['CJ19+244082+ Primary.jpg']}

推荐阅读