繁体   English   中英

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

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

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