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

how to know the index of a sublist with only one element

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

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

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

您可以使用 enumerate:

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]

这是另一种想法,可以得出您喜欢的结果。

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))))

输出:

[0, 1, 4, 5]