Method for indexing into a list by a number of dimensions

Viewed 37

I am writing code that uses nested lists. My list structure is essentially 2 elements, but the second element comprises two individual elements and so on and so forth. The size of the list therefore grows as 2^n + 1. Anyway, for each recursion of a function I need to be able to access any given element at some 'depth'. Usually, this would be trivial as given,

list1 = [[0,1], [[1,2], [1,0]]]

the following code:

list1[1][1]

would return:

[1,0]

However, for an n dimensional nested list (I use the word 'dimension' fairly haphazardly given that this is a nested list and not an array) I would surely need to 'exponentiate' my [1] index in order to index into each progressively 'deeper' nested list. Is there a trivial way to do this?

Thanks in advance, your help is greatly appreciated.

2 Answers

Use recursion:

def get(li, k):
    return get(li[1], k-1) if k > 0 else li

Or iteration:

def get(li, k):
    for _ in range(k):
        li = li[1]
    return li

I created this, I tried to make it as self explanatory as possible:

my_list = [[8,9], [[0,1], [[1,2], [1,0]]]]
# dim=1 -> [8,9]
# dim=2 -> [0,1]
# dim=3 -> [1,2]
# dim=4 -> [1,0]

def get_value_by_dimension(dim :int, lst: list):
    x = dim-1
    if x==0:
        return (lst[0])
    else:
        try:
            return get_value_by_dimension(x, lst[1])
        except:
            return "Dim is to high!"
print(get_value_by_dimension(2, my_list))
# [0, 1]

print(get_value_by_dimension(1, my_list))
# [8, 9]

print(get_value_by_dimension(5, my_list))
# Dim is to high!
Related