使用循环检查变量是否在字典中

2024-06-10 00:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

所以为了上课,我在做一个蹩脚的文本冒险游戏。我想对照我的可接受词词典检查用户输入的内容。但是,当我执行以下操作时,会得到一个“TypeError:”set“object is not subscriptable”。我该怎么解决这个问题?你知道吗

“游戏”的一小部分代码:

def butts():
    southLib={"long thing", "rough thing", "cylinder thing", "floor thing", "home"}

    userPoop = str(input("Would you like to poop in the long thing, rough thing, cylinder thing, floor thing, or home? None?"))

    while southLib[userPoop] == None:
        print("I do not understand")
        userPoop = str(input("Would you like to poop in the long thing, rough thing, cylinder thing, floor thing, or home? None?"))

butts()

Tags: noneyouhomeinputnotlongthingstr
2条回答

进行适当的安全壳检查。你知道吗

while userPoop not in southLib:

如果要检查某个内容是否不在集合中,只需使用not in运算符:

>>> my_set = {"foo", "bar", "baz"}
>>> "foo" not in my_set
False
>>> "qux" not in my_set
True

(类似地,您可以使用in检查集合中是否有的内容。)

相关问题 更多 >