如何在嵌套列表上筛选字符串列表?

2024-10-03 09:11:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要遍历文件名列表,并根据字典中的一组键检查每个字符串。你知道吗

在我的文件排序器中,我想根据文件名中的关键字对文件进行排序。 在下一步中,我需要根据找到的键值将文件移动到文件夹中。你知道吗

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

我希望输出是文件名及其键值的列表。你知道吗


Tags: intxthomeforfilesfilterfilenamefile
1条回答
网友
1楼 · 发布于 2024-10-03 09:11:46

如果我是对的,你想编一本字典。字典中的每个键都是筛选器的名称,这些键将是与该筛选器匹配的文件名列表。使用您已有的代码:

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']}

相关问题 更多 >