2015-06-18 86 views
1

我有一个列表,我想找到一个嵌套列表的索引使用元组(16,29,32,40)像字典之一。我如何找到嵌套列表中的列表的索引

list2 = [[(4, 8, 16, 29), 1, '[#1]:'], [(16, 29, 32, 40), 1, '[#2]:']] 
item_position = list2.index([(16, 29, 32, 40)]) #Error here! 
print("item_position", item_position) 

Output error: 
item_position = list2.index([(16, 29, 32, 40)]) 
ValueError: [(16, 29, 32, 40)] is not in list 

当列表是:

list2 = [[(4, 8, 16, 29), 1, '[#1]:'], [(16, 29, 32, 40)]] 

值:

item_position 1 

,所以我知道它可以工作。只是想知道是否有人能给我看正确的代码。 在此先感谢。

回答

0

一种方法是遍历你的清单,记住每个匹配项:

In [3]: item_position = [i for i, x in enumerate(list2) if x[0] == (16,29,32,40) ] 

In [4]: print("item_position", item_position) 
item_position [1] 
+0

谢谢,这工作。 – matt2605