Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do you return a list of indexes for an arbitarily nested element?

Say I have a list:

>>> nested=[[1, 2], [3, [4]]]

I am trying to get a function that would return [1,1,0] if I were looking for 4. If the specified element weren't in the list then it would return an empty list, [].

Nested could have any structure, so I am thinking some type of recursive function would be best, but am having trouble controlling for depth and breadth of the structure.

This is not working code, but along the lines of what I am thinking:

def locate(x,element,loc=[0],counter=0):
    for c,i in enumerate(x):
        if isinstance(i,list):
            locate(i,loc+[0],counter+1)
        else:
            loc[counter]=c
            if i==element: return loc

The function call would look something like this:

>>> locate(nested,4)
[1,1,0]

A recursive function might not be the best solution, but just my attempt.

like image 341
LMc Avatar asked Feb 06 '23 21:02

LMc


2 Answers

You might consider moving to some kind of tree data structure instead, but here's an example with your current data structure:

from collections import Iterable

def flatten(collection, depth=()):
    for i, element in enumerate(collection):
        if isinstance(element, Iterable) and not isinstance(element, str):
            yield from flatten(element, depth=depth + (i,))
        else:
            yield element, depth + (i,)

def locate(nested, element):
    for v, indices in flatten(nested):
        if v == element:
            return indices
like image 164
wim Avatar answered Feb 08 '23 11:02

wim


def nested_find(l, e):
    for i, x in enumerate(l):
        if isinstance(x, list):
            t = nested_find(x, e)
            if t:
                return [i] + t
        elif x == e:
            return [i]

This returns None if e not in l

like image 33
Patrick Haugh Avatar answered Feb 08 '23 11:02

Patrick Haugh