查找包含项目的列表的索引,也在列表中

时间:2014-12-31 08:20:13

标签: python list

我们的名单是这样的:

Inventory = [["Item","Quantity"]["Credits","5000"]["Item 1", 2]["Item 3",1]]

我想在列表的主列表中找到包含" Credits"的索引。

我目前的解决方案对我来说似乎有点不合适。在这段代码中,我有一个函数可以从这个列表中的每个项目中提取第一个项目(在其他情况下它很有用,我可以将它用于此用途)。所以它会给我[" Credits"," Item 1"," Item 2"]。我可以在此使用.index(" Credits")并减去1(因为该函数忽略了第一个标签项),但这感觉就像我跳过了一些不必要的箍。

工作,是的。但我希望有更好的东西。

2 个答案:

答案 0 :(得分:0)

您可以使用enumerate和列表理解:

>>> Inventory = [["Item","Quantity"],["Credits","5000"],["Item 1", 2],["Item 3",1]]
>>> [i for i,j in enumerate(Inventory) if j[0]=='Credits']
[1]

答案 1 :(得分:0)

>>> l = [["Item","Quantity"],["Credits","5000"],["Item 1", 2],["Item 3",1]]
>>> next( index for index,item in enumerate(l) if item[0] == "Credits")
1
相关问题