如何在Python2的列表中搜索多个短语

2024-06-13 11:25:54 发布

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

我正在做一个示例游戏。这是一个游戏,玩家键入一些东西,并根据他们键入的内容,一些新的事情发生。这是所有if-else语句,但我不知道如何在一个短语中搜索多个单词,而不是为相同的结果生成多个elif语句。你知道吗

def room_1(key):

Key = "False"

if key == "True":
    room1_choice = raw_input("Enter Command > ")

    if "door" in room1_choice:
        print "\nThe door lock clicks, and opens...\n"
        first_hall()

    elif "exit" in room1_choice:
        print "\nThe door lock clicks, and opens...\n"
        first_hall()

    elif "leave" in room1_choice:
        print "\nThe door lock clicks, and opens...\n"
        first_hall()

    elif "lamp" in room1_choice:
        print "\nNot sure what you want to do involving a key and a lamp...\n"
        room_1("True")

    else:
        print "\nUnknown command. This is not that hard...\n"
        room_1("True")

elif key == "False":
    room1_choice = raw_input("Enter Command > ")

    suicide = ['suicide', 'hotline']
    if "tape" in room1_choice:
        print "\nAs you remove the tape, the lamp falls on the ground."
        print "The bottom of the lamp breaks off revealing a key inside.\n"
        tape_removed("first")

    elif "shoot" in room1_choice:
        print "\nNo firearm located. That is dangerous...\n"
        room_1(Key)

    elif "kick" in room1_choice:
        print "\nYou attempt using violence, violence is never the answer.\n"
        room_1(Key)

    elif "lamp" in room1_choice:
        print "\nThe lamp is held to the wall using tape...\n"
        room_1(Key)

    elif "door" in room1_choice:
        print "\nThe door is locked.\n"
        room_1(Key)

    elif "your" in room1_choice:
        print "\nSuicide is never the answer.\n"
        room_1(Key)

    elif any(suicide in s for s in room1_choice):
        print "\nSuicide is never the answer.\n"
        room_1(Key)

    elif "kill" in room1_choice:
        print "\nNo! Killing is bad...\n"
        room_1(Key)

    else:
        print "\nUnknown command. Try something else.\n"
        room_1(Key)

elif key == "ignore":
    ignoring_key()

在第8行和第12行,我想把这两个组合成一个if语句。我尝试使用“any”函数,但仍然不起作用。非常感谢!


Tags: thekeyinifiselseroomprint
2条回答

使用any函数时,您的思路是正确的:

if any(d in room1_choice for d in ['door', 'exit', 'leave']):
    print "\nThe door lock clicks, and opens...\n"
    first_hall()

对于具有相同结果的条件,可以使用^{},例如:

if set(['door', 'exit', 'leave']).intersection([room1_choice]):
    print "\nThe door lock clicks, and opens...\n"
    first_hall()

相关问题 更多 >