如何在多个OR条件下比较用户输入PYTHON 3.x

问题描述

很抱歉,这是一个愚蠢的问题。我已经做了一些搜索,但是却找不到我需要的信息。我是python的新手。目前位于“学习Python 3困难方法”课程的中间。

我正在尝试编写一个IF语句,该语句采用用户生成的字符串,并将其与列表进行比较,然后如果存在匹配项,则求值为True。

我已经能够使用以下方法成功完成此任务:

if input in list:
    print("That was in the list.")

但是我现在想做的是交换这个位置,并使用IF语句中的一个列表。我正在做ZORK风格的游戏,其中房间的门在不同的墙壁等位置,因此在这种情况下,我没有一堆具有不同配置“ n”,“ s”,我必须参考其中的“ e”,“ w”,这取决于哪些墙壁上有门。但是我不想写出三个单独的elif评估,它们都做完全相同的事情(如果我为每个房间的每个“禁止”方向都写了一个)。希望所有这些都有意义。

我在某处读到您可以在IF语句中放入一个列表,例如{{up“,'down','left'},但是当我尝试说它在“ in”中没有字符串时, ”评估:

choice = input("> ")

if {'up','down','left','right'} in choice:
    print("You wrote a direction!")
else:
    print("Oh bummer.")

解决方法

所有您需要做的是使用列表[]方括号,而不是大括号(那些用于集合),并且需要向前移动选择变量。 (您希望看到choice在列表中,而不是相反。)

您的代码应为:

choice = input("> ")

if choice in ['up','down','left','right']:
    print("You wrote a direction!")
else:
    print("Oh bummer.")
,

顺序错误

if choice in {'up','right'}:
    print("You wrote a direction!")
else:
    print("Oh bummer.")

编辑:使用集进行存在检查通常比列表更有效

,

您可以使用any()来检查'up'变量中是否存在'down''left''right'choice字符串中的任何一个:

choice = input("> ")

if any(x in choice for x in {'up','right'}):
    print("You wrote a direction!")
else:
    print("Oh bummer.")

尽管输入格式通常由程序预先确定,所以您可以执行以下操作:

choice = input("> ")

# assuming the input is always in the format of "go <direction>"
direction = choice.split()[1]

if direction in {'up','right'}:
    print("You wrote a direction!")
else:
    print("Oh bummer.")

或者您可以使用regex(但这要复杂得多)