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

2024-05-20 03:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的清单的一个例子。 我想枚举此列表中的每个嵌套列表,并且仍然能够以相同格式打印列表列表。 在我枚举这些嵌套列表之后,我还想通过枚举来索引,以便通过数字搜索主列表。 这可能吗?你知道吗

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

我想列举一下“武器库”的清单,这样之后就可以:

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

Tags: 列表格式数字例子slingshotleatherswordsandals
3条回答

这个怎么样?使用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,以确定他们想要的项目。你知道吗

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

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

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

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

相关问题 更多 >