将 2 个列表中的字符与字符串匹配

Matching characters from 2 lists with strings

使用 python 我想执行以下操作

list1 = ['some text from a string (yes it is here too)', 'some more text 2', 'some more text 3 (with some parenthesis)']

list2 = ['string (yes it is here too)', 'text 2', '(with some parenthesis)']

并生成以下列表:

list3 = ['some text from a', 'some more', 'some more text 3']

在 python 3 中执行此操作的最佳方法是什么?

如果 list2 中的项目总是比 list1 中的项目更短(一部分)。你可以这样做:

list3 = []
for i,j in zip(list1,list2):
    list3.append(''.join(i.split(j)))

或一行:

list3 = [''.join(i.split(j)) for i,j in zip(list1,list2)]

如果 list2 中的项目数不等于 list1 中的项目数,则可以像这样从 list1 项目中删除 list2 项目的所有外观:

list3 = []
for i in list1:
    for j in list2:
        if j in i:
            i = ''.join(i.split(j))
    list3.append(i)

试试这个自制食谱。

list1 = ['some text from a string (yes it is here too)', 'some more text 2', 'some more text 3 (with some parenthesis)']

list2 = ['string (yes it is here too)', 'text 2', '(with some parenthesis)']
need = [[space for space in l1.split(l2) if space != ''] for l1,l2 in zip(list1,list2)]