Добавлю от себя примеры.
filter_list – стандартный алгоритм
filter_list_2 – стандартный алгоритм, переделанный в синтаксис генератора списка
filter_list_3 – использование функции фильтрации, которая будет применяться к каждому элементу
Код:
def filter_list(items, value):
has_more = items.count(value) > 1
new_items = []
for x in items:
# Если встретили элемент и он встречается больше одного раза
if x == value and has_more:
continue
new_items.append(x)
return new_items
def filter_list_2(items, value):
has_more = items.count(value) > 1
return [x for x in items if not (x == value and has_more)]
def filter_list_3(items, value):
has_more = items.count(value) > 1
return list(filter(lambda x: not (x == value and has_more), items))
if name == 'main':
items = ['cat', 'hello', 'dog', 'hello']
print(filter_list(items, 'hello'))
print(filter_list_2(items, 'hello'))
print(filter_list_3(items, 'hello'))
print()
print(filter_list(items, 'cat'))
print(filter_list_2(items, 'cat'))
print(filter_list_3(items, 'cat'))
Консоль:
['cat', 'dog']
['cat', 'dog']
['cat', 'dog']
['cat', 'hello', 'dog', 'hello']
['cat', 'hello', 'dog', 'hello']
['cat', 'hello', 'dog', 'hello']