python - 如何制作 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
解决方案
您的 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()
推荐阅读
- python - Django - 获取按不同属性分组的查询集列表对象属性
- react-native - 您如何识别 Expo Push Notification Token 所属的 Expo 项目?
- javascript - Google 脚本 - Array.sort - compareFunction 的操作数反转?
- excel - 从动态范围内的单元格中删除最后一个逗号
- c# - Xamarin C# 将双嵌套集合绑定到代码中的 Switch IsToggledProperty
- clojurescript - Clojure 脚本。发生重新渲染时重置 Reagent 中的原子
- angular - 类型 'never' 必须有一个返回迭代器的 '[Symbol.iterator]()' 方法。打字稿
- r - 打印以逗号分隔,删除引号并在 R 中添加特殊引号
- excel - 如何从正确的位置/格式中抓取图像并将其粘贴到 excel 中?
- python-3.x - 字节串解码的两种形式