Я пытаюсь составить список строк на основе другого списка подстрок. Я хочу удалить строки в списке1, если строка содержит подстроку в списке2.
list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']
Результат, который я хочу:
output = ['sandwich shop','grocery store']
Один из подходов состоит в том, чтобы перебрать копию list1
и удалить из нее строку, если она содержит подстроку из list2
.
list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']
#Iterate on copy of list1
for item1 in list1[:]:
#If substring is present, remove string from list
for item2 in list2:
if item2 in item1:
list1.remove(item1)
print(list1)
Другой подход состоит в том, чтобы найти совпадающие подстроки, а затем вычесть этот результат из фактического списка.
list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']
#List of strings where the substrings are contained
result = [item1 for item1 in list1 for item2 in list2 if item2 in item1 ]
#List of strings where the substrings are not contained, found by set difference between original list and the list above
print(list(set(list1) - set(result)))
Вывод будет таким же в обоих случаях, как показано ниже
['grocery store', 'sandwich shop']
Использование регулярного выражения.
Бывший:
import re
list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']
pattern = re.compile(r"|".join(list2))
print([i for i in list1 if not pattern.search(i)])
Выход:
['sandwich shop', 'grocery store']
Так много разных способов сделать это. Вот мой подход (возможно, не лучший).
list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']
list3 = [x for x in list1 if len(set(list2) & set(x.split())) == 0]
print(list3)
Дает тебе:
['sandwich shop', 'grocery store']
Что происходит?
split()
.len()
.
Это было так быстро. Спасибо.