Skip to main content
 首页 » 编程设计

Python 2.7之评估列表中的元素以在 for 循环中使用

2025年05月04日8落叶无声

大家好,我是 Python 的新手,我正在学习列表。

我正在编写一个小益智文字游戏,需要您使用基本命令从一个房间移动到另一个房间(功能到功能)。有些房间有陷阱,他们需要一个元素来移除陷阱。 E.G 房间里的熊要求你先找到蜂蜜,然后再给熊。我也了解如何 .remove() 和 .append() 列表。

我创建了 2 个列表:

inventory = ["Honey"] 
trap = ["Bear"] 

当我带着熊进入房间并拿到蜂蜜时,真棒,我可以通过,但是我如何制作一个循环或#Something#来检查“陷阱”列表,以便如果“熊”元素不存在在列表中,他们不需要蜂蜜通过,因为很明显,当他们用在熊身上时,我就从“库存”列表中删除了“蜂蜜”。理论是,如果他们离开房间并想重新进入,他们就不再需要蜂蜜了。

我想我的理解是这样的,假设你已经找到了蜂蜜:

def room1() 
    print "You are in ROOM 1" 
 
    if #item is not in list# and #bear is not in the room#: 
        room2() 
    elif #item is in the bag#: 
        print "You give the honey to the bear, and it is distracted" 
        inventory.remove("Honey") 
        trap.remove("Bear") 
        room2() 
    else: 
        print "You die to the bear" 
        exit() 

我真的很感激任何建议,甚至是解决这个问题的不同方法。 非常感谢!

请您参考如下方法:

使用in 成员运算符来确定一个元素是否在列表中。这不需要循环,它将测试每个元素。

if 'honey' in inventory and 'bear' not in trap: 
    room2() 
elif ...