有没有一种方法可以在Python的字符串中仅索引项目的一部分?

时间:2020-09-18 02:37:28

标签: python list indexing

我正在为学校的计算机科学/网络安全课程制作一款基于文本的无限生存游戏。我正在使用Python工作,并且有一个清单[]清单,我使用.append(item)将清单和物料添加到清单中。然后,我还使用单独的变量来实际赋予字符串含义,但这无关紧要。每个项目均以“项目,(项目数量)”格式写入库存清单。我需要知道是否可以使用.index()仅搜索列表中元素的“ item”部分,以便仅编辑元素的(item amount)部分,以及是否存在。我需要知道是否还有其他选择。最好不要撤销清单中列出的清单所使用的方法,因为很多游戏都是围绕该方法构建的。

materials = ["log", "stone", "sticks", "string", "junk", "rocks", "cloth", "herbs"]
inventory = []
def material_gathering():
    global health, hunger, log_amount, stone_amount, stick_amount, string_amount, junk_amount, rock_amount, cloth_amount, herb_amount
    material_type = random.choice(materials)
    material_amount = random.randint(2, 10)
    health = health - material_amount
    hunger = hunger + material_amount
    if material_type == "log":
        log_amount = log_amount + material_amount
        print("You gathered " + str(material_amount) + " logs.")
        if "log, " in inventory:
            log_position = inventory.index("log, ")
            inventory[log_position] = ("log, " + str(log_amount))
        else:
            inventory.append("log, " + str(log_amount))

1 个答案:

答案 0 :(得分:0)

感谢Green Cloak Guy的评论,使用字典的效果非常好,我将清单清单转换为字典,然后替换了所有清单。添加有清单[“ item”] = item_amount,这样它就删除了所有项目搜索和索引的需求,ETC。

相关问题