枚举包含字符串和整数的子列表 (python)

enumerating sublists that contain strings and integers (python)

这是我的列表示例。 我想枚举此列表中的每个嵌套列表,并且仍然能够以相同格式打印列表列表。 在我枚举这些嵌套列表之后,我还想通过枚举建立索引,以便按编号搜索主列表。 这可能吗?

weaponstore = [['Slingshot', 5, 20],['Leather Sandals', 5, 40],['Wooden Sword', 15, 100]]

我想枚举列表 'weaponstore',这样之后它将是:

weaponstore = [[0, 'Slingshot', 5, 20],[1,'Leather Sandals', 5, 40],[2,'Wooden Sword', 15, 100]]

使用理解和enumerate。 (创建一个新列表。)

[[i] + l for i, l in enumerate(weaponstore)]

或者原地。 (修改武器库。)

for i, l in enumerate(weaponstore):
    l.insert(0, i)

这个怎么样?使用 python 列表理解。

>>> [[i] +j for i, j in enumerate(weaponstore)]
[[0, 'Slingshot', 5, 20], [1, 'Leather Sandals', 5, 40], [2, 'Wooden Sword', 15, 100]]

将项目的索引存储在项目内部没有任何好处。看起来您可能只想将武器商店打印为编号列表,以便用户可以更轻松地选择他们想要的武器。与其将索引放入每个项目,不如在不更改数据结构的情况下显示它:

>>> weaponstore = [['Slingshot', 5, 20],['Leather Sandals', 5, 40],['Wooden Sword', 15, 100]]
>>> for idx,item in enumerate(weaponstore):
...     print('#{}: {}\nQuantity: {}\nCost: {}'.format(idx, *item))
...
#0: Slingshot
Quantity: 5
Cost: 20
#1: Leather Sandals
Quantity: 5
Cost: 40
#2: Wooden Sword
Quantity: 15
Cost: 100

这会遍历 weaponstore,并在每个项目上附加适当的索引。对于每个项目,它将打印一个格式化字符串,将传递的参数插入大括号中。

您可能想使用 .format(idx+1, ... 而不是 idx,这样列表以更自然的 1 开头。然后,您将从用户输入的任何数字中减去 1 以确定他们想要的项目。

如果您正在寻找一种从标识符获取武器库中武器的方法,那么您应该查看字典:

weaponstore = {
    id1: ['Slingshot', 5, 20],
    id2: ['Leather Sandals', 5, 40],
    id3: ['Wooden Sword', 15, 100]
}

允许访问:

weaponstore[id1]   # once they know what the id is

现在您可以使用原始列表中的初始位置作为它们的 id,但这非常脆弱,当您从商店中 add/remove 一件商品时很容易损坏。 id 可以是任何(可散列的)对象,因此您可以使用武器名称作为它的 id:

weaponstore = {
    'Slingshot: [5, 20],
    'Leather Sandals': [5, 40],
    'Wooden Sword': [15, 100]
}

现在可以访问了:

weaponstore['Slingshot']

你可以走得更远,把细节也写成字典:

weaponstore = {
    'Slingshot',: {'quantity': 5, 'cost': 20},
    'Leather Sandals': {'quantity': 5, 'cost': 40},
    'Wooden Sword': {'quantity': 15, 'cost': 100}
}

weaponstore['Slingshot]['cost'] == 20

您可以遍历商店中的商品:

for weapon, details in weaponstore.items():
    print(weapon, details)

但是很难从你的描述中判断出你的需求是什么