2

Есть список:

listt = ['testzxc','someqwe','thisert']
key = 'test'

Надо удалить значение в list, если есть вхождение по key.
Можно сделать, например, через filter или lambda?

Вот мое решение, обычное:

listt = ['testzxc', 'someqwe', 'thisert']
new_listt = []
key = 'test'
for item in listt:
    if key in item:
        next
    new_listt.append(item)
print(new_listt)

PS Хочу сделать это через while или for, но есть ли магия python, какое-то изящное решение?

1
  • 1
    ваш код не работает. замените next на continue
    – TigerTV.ru
    16 фев 2021 в 20:41

2 ответа 2

6

Можно и с filter, и с lambda:

key = 'test'
my_list = ['testzxc', 'someqwe', 'thisert']

new_list = list(filter(lambda i: key not in i , my_list))
>>> new_list
['someqwe', 'thisert']

но старый добрый list comprehension все же понятнее, как по-мне:

new_list = [i for i in my_list if key not in i]
2
  • 1
    используй not in
    – TigerTV.ru
    16 фев 2021 в 20:51
  • 1
    @TigerTV.ru спасибо, у автора там if key in item, поэтому, наверное
    – Jack_oS
    16 фев 2021 в 20:57
3

Через filter:

listt = ['testzxc','someqwe','thisert']
key = 'test'
*listt, = filter(lambda x: x.find(key) == -1, listt)
print(listt)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.