如何测试变量不等于多个值?

24

这是我拥有的代码:

choice = ""

while choice != "1" and choice != "2" and choice != "3": 
    choice = raw_input("pick 1, 2 or 3")

    if choice == "1":
        print "1 it is!"

    elif choice == "2":
        print "2 it is!"

    elif choice == "3":
        print "3 it is!"

    else:
        print "You should choose 1, 2 or 3"
虽然它能够正常工作,但我觉得循环条件特别笨拙。如果我有更多可接受的选择,有没有更好的方法来编写这个条件语句呢?

你是否总是打印 choice, "it is" (?),还是这些确实是不同的情况? - Andy Hayden
@hayden 实际代码非常不同,我只是简化了它以使问题更清晰。 - M830078h
1
我知道它被简化了(干得好),但我的问题更多是:如果是1则进行f(),如果是2则进行g(),而不是如果是1或2,则进行f()。既然您接受了答案,这些就不能真正分开处理 :)。 - Andy Hayden
7个回答

59

通过检查元素是否在选择列表中,可以对while部分进行重构,使代码更加简洁:

while choice not in [1, 2, 3]:

这是在检查choice的值是否不在那个列表中的元素


10
作为一条注记,这里使用集合字面值({1, 2, 3})可能更合理,因为顺序并不重要,并且在集合上执行成员检查比在列表上更快。虽然这可能不会真正起到作用,但出于风格考虑,最好交换括号。 - Gareth Latty

6
您可以将逻辑推入循环中,并替换原有内容。
while choice != "1" and choice != "2" and choice != "3": 

使用

while True:

然后初始行的 choice = "" 是不必要的。然后,在每个分支中,一旦你完成了想做的事情,就可以使用 break


@hayden:?我并不建议他从循环内删除代码。 - DSM
我试图避免在这里使用 while True,主要是因为我不想有无尽的循环,而且由于某种原因我没有想到 break。不过我会在我的代码中实际使用你的建议,尽管 Suhail Patel 的答案更符合问题。谢谢! - M830078h
1
@M830078h:我对使用这样的成员测试有问题,因为如果你决定添加一个新的情况(比如说“4”),现在你必须在两个地方添加。这是DRY(不要重复自己)原则的违反,而且当我提交这些代码时通常会引入错误。 - DSM

4
我认为类似这样的东西会更好。
possilities = {"1":"1 it is!", "2":"2 it is!", "3":"3 it is!"} 
choice = ""

while True:
    choice = raw_input("pick 1, 2 or 3")
    if choice in possilities:
        print possilities[choice]
        break
    else:
        print "You should use 1, 2 or 3"

1
我建议添加一个函数,该函数会一直循环,直到选择了有效选项,然后返回所选值。
这意味着您的其余代码不应在while内部,保持所有内容平整("平整比嵌套更好")。
def get_choice(options):
    """Given a list of options, makes the user select one.

    The options must be strings, or they will never match (because raw_input returns a string)

    >>> yn_choices = ['y', 'n']
    >>> a = get_choice(options = yn_choices)
    """
    prompt_string = "Pick " + ", ".join(options)
    while True:
        choice = raw_input(prompt_string)
        if choice in options:
            return choice
        else:
            print "Invalid choice"

# Prompt user for selection
choice = get_choice(["1", "2", "3"])

# Do stuff with choice...
if choice == "1":
    print "1 it is!"

elif choice == "2":
    print "2 it is!"

elif choice == "3":
    print "3 it is!"

else:
    print "You should choose 1, 2 or 3"

1

您可以使用字典将1映射到当值为1时要执行的代码,以此类推...这样,您就可以摆脱if语句,并且通过简单更新字典来支持将来的其他值。至于while中的条件,您只需检查键是否在字典中即可。


0

我认为你可以使用一个包含所有可能选择的集合,并使用“in”表达式来判断while部分。

至于if-else部分,打印(choice,“它是!”)就可以了。


-1

while str(choice) not in "123" .....

当str(choice)不在“123”中时 .....


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接