我可以让Python检查我的列表以查看用户输入是否使用if语句在列表中包含字符串?如果没有其他选择?

问题描述 投票:0回答:1

Python的初学者,但我想使用一个列表包含用户可能在输入中给出的多个潜在的字符串响应。

def Front_Door():
    print("Welcome to the Party Friend!")
    Emotional_state = input("How are You Today?  ")
    Positive_Emotion = ["good", "fine", "happy"]

[我试图使用if语句来获取python来检查我的列表,以查看输入内容是否包含例如中列出的任何字符串。我给了。

if Positive_Emotion in Emotional_state:
    print("That's Great! Happy to have you here!")

代码仍然设法提示我输入Emotional_state,但它只重复了一次该问题,如果我用我再次列出的字符串之一作为响应,则会出现此错误:

if Positive_Emotion in Emotional_state:
TypeError: 'in <string>' requires string as left operand, not list

我猜想有一种方法可以让Python在我的字符串列表中进行搜索,并将其与输入进行交叉引用,并给我所需的响应?

感谢您的帮助:)。

python-3.x list if-statement
1个回答
0
投票

您正在检查整个列表是否在字符串中!您可能想要做的就是检查列表中是否有任何项目在字符串中。

类似:

if any( [emotion in Emotional_state for emotion in Positive_Emotion] ):
    print("That's Great! Happy to have you here!")

这将检查列表中的每个情感,如果其中的any在字符串中,它将返回True。

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.