【问题标题】:How to make an if statement to check if all three items in list is present in another list如何制作 if 语句来检查列表中的所有三个项目是否都存在于另一个列表中
【发布时间】:2021-12-18 07:51:26
【问题描述】:

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

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

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

【问题讨论】:

  • 那些while 循环在做什么?此外,您可能希望将print("you won") 置于 for item in endgame: 循环之外。
  • 您应该在决定是否获胜之前检查您是否拥有所有物品。目前,您检查第一个项目并在那里做出决定,然后是输赢。 'wallet' 是第一项,它的存在才是最重要的。您应该改为检查 set(inventory) == set(endgame)

标签: python if-statement inventory text-based


【解决方案1】:

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

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

【讨论】:

  • 我爱你! (◕‿◕)♡
猜你喜欢
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
相关资源
最近更新 更多