简体   繁体   English

检查元素是否存在时获取子列表的索引

[英]Get the index of the sublist when checking for the existence of an element

As a continuation for this question , how can I get the index of the sublist which contains the element?作为这个问题的延续,我怎样才能获得包含该元素的子列表的索引?

So for example if I have:例如,如果我有:

a = [[1,2],[3,4],[5,6]]
any(2 in i for i in a)
....

How can I get 0 as a result (Because a[0] contains the number 2)?结果如何得到 0(因为 a[0] 包含数字 2)?

Alternatively, you can try this too:或者,你也可以试试这个:

for idx, sublst in enumerate(a):
    if 2 in sublst: 
        print(idx)

Output: Output:

0

Simple list comprehension which iterates over list with indexes using enumerate() will do the trick:使用enumerate()对带有索引的列表进行迭代的简单列表推导可以解决问题:

res = [i for i, el in enumerate(a) if 2 in el]

You can achieve same using regular for loop:您可以使用常规for循环实现相同的目的:

res = []
for i, el in enumerate(a):
    if 2 in el:
        res.append(el)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM