mael Delaunay
mael Delaunay

Reputation: 13

How do I access the nth nested list, were I know the depth of nested lists?

In a general case I'm classifying data points in nested lists with variable depths of nested loops, for example in a simple case :

alist = [ [[a, b], [c, d]],  [[e, f], [g, h]] ]

I use this to have operations like brackets, for example :

min ([ max([a, b]), max([c,d]) ])

However the problem I encounter is that in my example I reference [a, b] and [c, d], but I want to reference these as variables or indexes of a list in the case were we have a known depth of nested lists and known number of elements in the deepest nested brackets.

With what I know about using list indexes, I don't see how I can reference a nth depth in a nested list. If I wanted to reference the third nested list I have to explicitly write:

nlist[0][0][i]

And therefore if the depth varies, I can't do anything.

Upvotes: 0

Views: 318

Answers (1)

trincot
trincot

Reputation: 350272

You'll need to know more than just the depth. Like in your final example, you need to have 3 values: 0, 0, i.

In the generic case you would need to know n indices.

So you could write a little helper function that takes those indices as argument:

def deep_get(lst, *indices):
    for i in indices:
        lst = lst[i]
    return lst

And now when you have a list indices you can do:

indices = [0, 0, i]
# ...
# ...
print(deep_get(lst, *indices))

Setting

If you need to set a value instead of getting it, then use this function:

def deep_set(lst, value, *indices):
    for i in indices[:-1]:
        lst = lst[i]
    lst[indices[-1]] = value

Call as:

indices = [0, 0, i]
# ...
# ...
newValue = 9
print(deep_set(lst, newValue, *indices))

Upvotes: 1

Related Questions