[英]How to filter list of strings over nested lists?
我需要遍歷文件名列表,並對照字典中的一組鍵檢查每個字符串。
在文件排序器中,我想根據文件名中的關鍵字對文件進行排序。 在下一步中,我需要根據找到的鍵值將文件移動到文件夾中。
file_list = [
'01012007-1_employer_finance.txt',
'25102013-2_cargo_manifest.txt',
'12022018-3_epmloyer_home_adress.txt',
'12022028-4_epmloyer_work_adress.txt',
'01012011-5_employer_finance.txt'
'01012007-12_employer_finance.txt',
'25102013-23_cargo_manifest.txt',
'12022018-34_epmloyer_home_adress.txt',
'12022028-45_epmloyer_work_adress.txt',
'01012011-56_employer_finance.txt'
]
filelist = {
'file1':'01012007-1_employer_finance.txt',
'file2':'25102013-2_cargo_manifest.txt',
'file3':'12022018-3_epmloyer_home_adress.txt',
'file4':'12022028-4_epmloyer_work_adress.txt',
'file5':'01012011-5_employer_finance.txt',
'file6':'01012007-12_employer_finance.txt',
'file7':'25102013-23_cargo_manifest.txt',
'file8':'12022018-34_epmloyer_home_adress.txt',
'file9':'12022028-45_epmloyer_work_adress.txt',
'file10':'01012011-56_employer_finance.txt'
}
"""Dictionary files"""
filters = {
'finance': ['employer','finance'],
'manifest': ['manifest'],
'address': ['epmloyer', 'adress', 'home'],
'address': ['epmloyer', 'adress', 'work']
}
"""Tweede oplossing op stackoverflow"""
"""Loop through the nested list"""
def matches(filter, filename):
return all(x in filename for x in filter)
def get_filename(filter, files):
for f in files:
if matches(filter, f):
return f
for label, filter in filelist.items():
file = get_filename(filter, filelist)
if file:
print(f'Found {label} file: {file}')
pass
found_files = {label: get_filename(filter, filelist) for label, filter in filters.items()}
print(found_files)
filenamelist loop --> object bestandsnaam
filter dictory for loop
我希望輸出是文件名及其鍵值的列表。
如果我對,您想創建一個字典。 字典中的每個鍵都是過濾器的名稱,這些鍵將是與該過濾器匹配的文件名列表。 使用您已經擁有的代碼:
result = {key: [] for key in filters}
for fil in file_list:
for f in result:
if matches(filters[f], fil):
result[f].append(fil)
結果,您將得到:
{'finance': ['01012007-1_employer_finance.txt', '01012011-5_employer_finance.txt01012007-12_employer_finance.txt', '01012011-56_employer_finance.txt'],
'manifest': ['25102013-2_cargo_manifest.txt', '25102013-23_cargo_manifest.txt'],
'address': ['12022028-4_epmloyer_work_adress.txt', '12022028-45_epmloyer_work_adress.txt']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.