Skip to content Skip to sidebar Skip to footer

Python: Accessing Elements Of Multi-dimensional List, Given A List Of Indexes

I have a multidimensional list F, holding elements of some type. So, if for example the rank is 4, then the elements of F can be accessed by something like F[a][b][c][d]. Given a l

Solution 1:

You can use the reduce() function to access consecutive elements:

from functools import reduce  # forward compatibilityimportoperatorreduce(operator.getitem, indices, somelist)

In Python 3 reduce was moved to the functools module, but in Python 2.6 and up you can always access it in that location.

The above uses the operator.getitem() function to apply each index to the previous result (starting at somelist).

Demo:

>>>import operator>>>somelist = ['index0', ['index10', 'index11', ['index120', 'index121', ['index1220']]]]>>>indices = [1, 2, 2, 0]>>>reduce(operator.getitem, indices, somelist)
'index1220'

Solution 2:

Something like this?

def get_element(lst, indices):
    if indices:
        return get_element(lst[indices[0]], indices[1:])
    return lst

Test:

get_element([[["element1"]], [["element2"]], "element3"], [2])
'element3'
get_element([[["element1"]], [["element2"]], "element3"], [0, 0])
['element1']

Or if you want an iterative version:

def get_element(lst, indices):
    res = lst
    for index in indices:
        res = res[index]
    return res

Test:

get_element([[["element1"]], [["element2"]], "element3"], [1, 0])
['element2']

Post a Comment for "Python: Accessing Elements Of Multi-dimensional List, Given A List Of Indexes"