【问题标题】:How to delete an string from a list if it has an specific word in it如果列表中包含特定单词,如何从列表中删除字符串
【发布时间】:2019-02-19 15:25:34
【问题描述】:

我正在尝试编写一段代码,帮助我根据我的饥饿程度和剩余时间来选择早餐吃什么(新手个人项目: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"]

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

【问题讨论】:

    标签: string list python-3.7


    【解决方案1】:

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

    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']
    

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多