检查列表 A 中的字符串是否存在于列表 B 中(通过正则表达式)

问题描述 投票:0回答:1
listA = ['Leonardo_da_Vinci', 'Napoleon', 'Cao_Cao', 'Elton_John']
listB = ['123_Leonardo_da_Vinci_abc.csv', '456_Cao_Cao_def.csv']

listC = ['Napoleon', 'Elton_John']

我想检查

listB
中的项目是否包含
listA
中的值,并返回
listC
(即
listB
中缺少的列表)。为此,我想使用正则表达式(而不是其他启发式),例如(检查
Leonardo_da_Vinci
的示例):
.*Leonardo_da_Vinci.*

python list search
1个回答
0
投票

像这样的东西:

import re

def exists_csv_with_name(name:str, source_list: list) -> bool:
    regex = re.compile(fr'.*{name}.*')
    return any(regex.match(source_str) for source_str in source_list)
    
listC = [name for name in listA if not exists_csv_with_name(name, listB)]
© www.soinside.com 2019 - 2024. All rights reserved.