如果其中包含特定单词,如何从列表中删除字符串
How to delete an string from a list if it has an specific word in it
我正在尝试编写一段代码,帮助我根据自己的饥饿程度和剩余时间来选择早餐吃什么(新手个人项目: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]
因此,如果我输入 "I'm really hungry" 但输入 "Have little time",则应编辑列表,删除其中包含单词 "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"]
抱歉,如果我的代码看起来很糟糕或者我真的搞砸了任何语法。
如果能收到任何答案并解释它为什么有效以及我在哪一部分搞砸了,我将非常感激。
您可以使用列表理解来过滤列表以排除包含特定单词或短语的字符串。例如:
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']
我正在尝试编写一段代码,帮助我根据自己的饥饿程度和剩余时间来选择早餐吃什么(新手个人项目: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]
因此,如果我输入 "I'm really hungry" 但输入 "Have little time",则应编辑列表,删除其中包含单词 "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"]
抱歉,如果我的代码看起来很糟糕或者我真的搞砸了任何语法。 如果能收到任何答案并解释它为什么有效以及我在哪一部分搞砸了,我将非常感激。
您可以使用列表理解来过滤列表以排除包含特定单词或短语的字符串。例如:
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']