您可以使用next
和enumerate
:
>>> list1 = [(12, "AB", "CD"), (13, "EF", "GH"), (14, "IJ", "KL")]
>>> next(i for i,x in enumerate(list1) if 13 in x)
1
使用简单的 for 循环:
for i, item in enumerate(list1):
if 13 in item:
print i
break
...
1
更新:
如果每个元组中的第一项是唯一的并且您要多次执行此操作,则首先创建一个字典。字典提供O(1)
查找,而列表O(N)
>>> list1 = [(12, "AB", "CD"), (13, "EF", "GH"), (14, "IJ", "KL")]
>>> dic = {x[0]:x[1:] for x in list1}
访问项目:
>>> dic[12]
('AB', 'CD')
>>> dic[14]
('IJ', 'KL')
#checking key existence
>>> if 17 in dic: #if a key exists in dic then do something
#then do something