python - 如何将列表中的匹配元素附加到另一个列表?
问题描述
我有两个清单:
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)```
解决方案
您可以将所有内容存储在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']}
推荐阅读
- vue.js - 如何将数组中的 mutil 对象与 lodash 合并?
- python - 如何在 1 的距离内找到字典中的字符串变体?
- unit-testing - 在 .net core Ihostedservice 上编写单元测试的好习惯是什么?
- excel - 如何在 Excel VBA/宏中处理 CTRL-V?
- visual-studio-code - Visual Studio Code 的键映射
- excel - 根据动态用户范围绘制图表
- ios - collectionView 分为三行 swift 4
- google-analytics - 不良事件跟踪代码 - Google Analytics
- javascript - 在显示当前图像时从阵列内的剩余图像中随机选择
- r - 数据帧的每 n 列的总和