[英]Get the index of the sublist when checking for the existence of an element
作為這個問題的延續,我怎樣才能獲得包含該元素的子列表的索引?
例如,如果我有:
a = [[1,2],[3,4],[5,6]]
any(2 in i for i in a)
....
結果如何得到 0(因為 a[0] 包含數字 2)?
或者,你也可以試試這個:
for idx, sublst in enumerate(a):
if 2 in sublst:
print(idx)
Output:
0
使用enumerate()
對帶有索引的列表進行迭代的簡單列表推導可以解決問題:
res = [i for i, el in enumerate(a) if 2 in el]
您可以使用常規for循環實現相同的目的:
res = []
for i, el in enumerate(a):
if 2 in el:
res.append(el)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.