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

rta7y2nd  于 2023-03-06  发布在  Python
关注(0)|答案(1)|浏览(167)
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中缺少的列表)。为此,我想使用regex(没有其他启发式),如(检查Leonardo_da_Vinci的示例):.*Leonardo_da_Vinci.*

lokaqttq

lokaqttq1#

大概是这样的

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)]

相关问题