簡體   English   中英

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

[英]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]

您可以嘗試枚舉,只是為了娛樂,您也可以玩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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM