如何过滤嵌套列表中的字符串列表?

时间:2019-01-22 17:30:08

标签: python python-3.x

我需要遍历文件名列表,并对照字典中的一组键检查每个字符串。

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

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

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

1 个答案:

答案 0 :(得分:1)

如果我对,您想创建一个词典。字典中的每个键都是过滤器的名称,这些键将是与该过滤器匹配的文件名列表。使用您已经拥有的代码:

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