您如何知道子列表中元素的索引 [英] How do you know the index of an element that in the sub list

查看:73
本文介绍了您如何知道子列表中元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何知道子列表中元素的索引? 在这里提出了类似的问题用于不嵌套的列表

How do you know the index of an element that is in a sub list? A similar question was asked here for lists without nesting

像这样:

L=[[1, 2, 3], [4, 5, 6]]

当元素为3时我想作为输出的内容:

What I want to be as output when the element is 3:

output=[0][2]

推荐答案

尝试一下:

def get_sublist_index(lists, item):
    for sublist in lists:
        if item in sublist:
            return lists.index(sublist), sublist.index(item)

>>> L=[[1,2,3],[4,5,6]]
>>> get_sublist_index(L, 3)
(0, 2)

或者获取每一项:

def get_sublist_index(lists, item):
    for sublist in lists:
        if item in sublist:
            yield lists.index(sublist), sublist.index(item)

制作生成器:

>>> L=[[1,2,3],[4,3,6]]
>>> get_sublist_index(L, 3)
<generator object get_sublist_index at 0x1056c5e08>
>>> [i for i in get_sublist_index(L, 3)]
[(0, 2), (1, 1)]

或者如果您不需要发电机:

Or if you don't want a generator:

def get_sublist_index(lists, item):
    outList = []
    for sublist in lists:
        if item in sublist:
            outList.append((lists.index(sublist), sublist.index(item)))
    return outList

>>> get_sublist_index(L, 3)
[(0, 2), (1, 1)]
>>> 

这篇关于您如何知道子列表中元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆