Python 如何知道只有一个元素的子列表的索引

Python 如何知道只有一个元素的子列表的索引,python,list,indexing,sublist,Python,List,Indexing,Sublist,问题是我想知道只有一个元素的子列表的索引。例如: list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),] 我想知道“CORA”出现的子列表的索引。您可以使用枚举: list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), (

问题是我想知道只有一个元素的子列表的索引。例如:

list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),]

我想知道“CORA”出现的子列表的索引。

您可以使用
枚举

list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),]
index = [i for i, [a, _] in enumerate(list1) if a == 'CORA']
输出:

[0, 1, 4, 5]
[0, 1, 4, 5]

您可以使用
枚举

list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),]
index = [i for i, [a, _] in enumerate(list1) if a == 'CORA']
输出:

[0, 1, 4, 5]
[0, 1, 4, 5]

这是另一个你喜欢的结果

list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),]
result = []
#print(list(result.append(index) or 'Processed' for index in range(0, len(list1))))
print(list(result.append(index) or 'Found' if list1[index][0] == 'CORA' else 'NotFound' for index in range(0, len(list1))))
print(result)
输出:

['Found', 'Found', 'NotFound', 'NotFound', 'Found', 'Found', 'NotFound']
[0, 1, 4, 5]
[Finished in 0.173s]

这是另一个你喜欢的结果

list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),]
result = []
#print(list(result.append(index) or 'Processed' for index in range(0, len(list1))))
print(list(result.append(index) or 'Found' if list1[index][0] == 'CORA' else 'NotFound' for index in range(0, len(list1))))
print(result)
输出:

['Found', 'Found', 'NotFound', 'NotFound', 'Found', 'Found', 'NotFound']
[0, 1, 4, 5]
[Finished in 0.173s]

你可以试试enumerate,只是为了好玩,你也可以玩lambda

print(list(filter(lambda x:x!=None,map(lambda x:list1.index(x) if 'CORA' in x else None ,list1))))
输出:


你可以试试enumerate,只是为了好玩,你也可以玩lambda

print(list(filter(lambda x:x!=None,map(lambda x:list1.index(x) if 'CORA' in x else None ,list1))))
输出: