Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you know the index of an element that in the sub list

Tags:

python

list

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

Like so:

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

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

output=[0][2]
like image 863
Vasco Figueiroa Avatar asked Dec 18 '22 11:12

Vasco Figueiroa


2 Answers

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

a = 3

print([(i,j) for i,x in enumerate(L) if a in x for j,b in enumerate(x) if b == a])
#[(0, 2), (2, 1), (2, 4)]

using list comprehension you can dig and return all the sub values. If you need to go deeper just keep chaining the list comprehension or write a function to do it.

like image 84
MooingRawr Avatar answered Mar 08 '23 03:03

MooingRawr


Try this:

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)

Or to get every item:

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

Making a generator:

>>> 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)]
>>> 
like image 45
rassar Avatar answered Mar 08 '23 03:03

rassar