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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With