如果其中包含特定单词,如何从列表中删除字符串

时间:2019-02-19 15:25:35

标签: string list python-3.7

我正在尝试编写一段代码,以帮助我根据自己的饥饿程度和剩余时间选择早餐吃什么(新手个人项目:p)。

问题是,如果我真的很饿,但是没有时间或几乎没有时间,我想删除一些带有“ avena”一词的选项。

这是代码(我不会在这里写下全部,只是我遇到问题的部分):

ptiempo_bebi = ["Leche fría con punchao", "Leche fría con avena", "Leche 
fría con cereal", "Yogurt con cereal", "Yogurt solo"]
mtiempo_bebi = ["Té", "Agua hervida con punchao", "Leche caliente con avena", "Yogurt con avena cocida"]
bebi = [ptiempo_bebi, mtiempo_bebi]

因此,如果我输入“我真的很饿”但输入“时间很少”,则应编辑列表,删除其中每个带有“ avena”字样的字符串。

我尝试了很多事情,但是这个问题困扰了我3天:(。

尝试使用功能和.remove

def searchword(lists, word):
   for element in lists:
      for palabra in element:
         if palabra == word:
           lists = lists.remove(element)
           return lists
print(searchword(ptiempo_bebi, "avena"))

尝试使用类似的功能,但使用del和append

for element in ptiempo_bebi:
    for palabra in element:
        if palabra == "avena":
            del(element)
        else:
            ptiempoedit_bebi.append(element)

我什至尝试(理解并)使用列表理解

ptiempobebiedit = [ptiempo_bebi.remove(element) for palabra in element for element in list if palabra == "avena"]

ptiempo_bebi = [ elem for elem in ptiempo_bebi if elem == "avena"]

对不起,如果我的代码看起来很糟糕,或者我真的搞砸了任何语法。 我非常感谢收到任何答案,并解释了为什么它起作用以及我弄乱了哪一部分。

1 个答案:

答案 0 :(得分:0)

您可以使用列表理解功能过滤列表以排除包含特定单词或短语的字符串。例如:

phrases = ['Té', 'Agua hervida con punchao', 'Leche caliente con avena', 'Yogurt con avena cocida']

filtered = [phrase for phrase in phrases if 'avena' not in phrase]
# ['Té', 'Agua hervida con punchao']