python中长文本的特定单词搜索

一个非常基本的问题,但是我有没有办法在包含我想要的单词的列表中提取一个字符串?就像是:

wordNeeded=str(input("blue or red?"))

list1=["A blue car", "A blue bike", "A red bike"]

然后提取包含wordNeeded中确切单词的字符串?

评论
  • Wood
    Wood 回复

    在其他方式中,您可以使用列表推导:

    list1 = ["A blue car", "A blue bike", "A red bike"]
    result = [item for item in list1 if wordNeeded in item]
    print(result)
    # ["A red bike"]
    

    Alternatively, you could look into filter in combination with a lambda function.