首页 > 解决方案 > 如何制作 if 语句来检查列表中的所有三个项目是否都存在于另一个列表中

问题描述

这是我正在尝试构建的一个简单示例,我不知道为什么“钱包”和“戒指”的组合可以作为胜利传递。

我希望玩家获得所有三个物品才能获胜。您对此提出了更好的解决方案吗?

import sys
inventory = []
def addtoInventory(item):
    inventory.append(item)

def room():
    print('you are in a living room, you say a card. Pick it up?')
    pickup = input()
    while pickup:
        if pickup == 'yes':
            addtoInventory("card")
            secondroom()
        else:
            print("you didnt pick it up")
            secondroom()
def secondroom():
    print('you are now in bedroom, theres a wallet, pick it up?')
    pickup = input()
    while pickup:
        if pickup == 'yes':
            addtoInventory("wallet")
            bathroom()
        else:
            print("you didnt pick it up")
            bathroom()
def bathroom():
    print('you are now in bathroom, theres a ring, pick it up?')
    pickup = input()
    while pickup:
        if pickup == 'yes':
            addtoInventory('ring')
            mall()
        else:
            print("you didnt pick it up")
            mall()
 
def mall():
    endgame = ["wallet", "card", "ring"]
    print('you are about to get a taxi to the pawn shop. do you have everything you need?')
    answer = input()
    print(inventory)
    while answer:
        if answer == 'yes':
            for item in endgame:
                if item not in inventory:
                    print("you lose")
                    sys.exit()
                else:
                    print("you won")
                    sys.exit()
            else:
                print("you lose")
                break

标签: pythonif-statementinventorytext-based

解决方案


您的 for 循环:for item in endgame在检查结束游戏中的第一项后,在 else 条件下停止程序。如果您需要所有 3 件物品都在库存中,您应该等待循环结束以宣布获胜,或者在一次测试中检查所有物品(没有循环):

if all(item in inventory for item in endgame):
   print('you Win')
else:
   print('you Lose')
sys.exit()

推荐阅读