【问题标题】:how to check if there is content in multiple indexes of a list in one statement (python)如何在一个语句中检查列表的多个索引中是否有内容(python)
【发布时间】:2014-09-24 01:40:00
【问题描述】:

我正在为我正在制作的基于文本的 RPG 创建一个库存装备系统。实际库存是一个包含 5 个索引的列表。我游戏中的每件物品都只能放入物品栏的特定槽位,例如,一把剑可以放入第一个槽位(仅限近战武器)和两个杂项槽位中的任何一个。

如果玩家决定在游戏中捡起一件物品,而它恰好是一把剑,代码如下:

Inventory = [None] * 5
def PickUpItem(self):
    if self.Slot == 1:
        if not Inventory[0]:
            Inventory[0] = self.Name

所以我检查了剑槽是否为空且可用,但如果不是,我想检查索引 3 或 4 是否为空且可用。然后,如果可能的话,我想将把剑放入可用索引(将项目放入空的 Misc 插槽)。

可以这样做吗?

谢谢!

【问题讨论】:

    标签: python list indexing


    【解决方案1】:

    您可以使用列表推导来构建可用索引的列表,然后选择该项目可以进入的第一个。这是一个例子:

    inventory_test.py

    inventory = [ 'full', None, 'full', None, None ]
    melee_indices = ( 0, 3, 4 )
    
    def add_item(name):
        indices = [ i for i in melee_indices if inventory[i] is None]
    
        if len(indices) > 0:
            inventory[indices[0]] = name
            return True
    
        return False
    
    print repr(inventory)
    
    add_item('sword')
    
    print repr(inventory)
    

    结果:

    ['full', None, 'full', None, None]
    ['full', None, 'full', 'sword', None]
    

    【讨论】:

    • 能否请您解释一下您的代码是如何工作的,主要是新的indices 列表,我不太明白它的用途。请解释一下 if 语句。
    • 索引列表包含库存列表中None 的索引。 if 语句确保实际上存在任何索引,以便indices[0] 不会引发越界错误。
    【解决方案2】:

    不知道jparonson的代码比我写的下面的代码效率高还是低:

    Inventory = [None] * 5
    
    def PickUpItem(self):
        if self.Slot == 1:
            if not Inventory[0]:
                Inventory[0] = self.Name
            elif not Inventory[3]:
                Inventory[3] = self.Name
            elif not Inventory[4]:
                Inventory[4] = self.Name
            else:
                print(PlayerName, 'cannot carry any more with him!')
    

    请记住,在游戏后期,总共可能有五个杂项插槽/索引。

    但就目前而言,我想我会等到那个时候再做进一步的测试。谢谢!

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 2011-02-10
      相关资源
      最近更新 更多