geo909 geo909 - 1 year ago 150
Python Question

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


Given a list
, I would like to access
. My problem is that my rank is going to be changing, so I cannot just have

Ideally, I would like to be able to do
and get the element
. I think something like this can be done with numpy, but for the types of arrays that I'm using, numpy is not suitable, so I want to do it with python lists.

How can I have something like the above?

EDIT: For a specific example of what I'm trying to achieve, see the demo in Martijn's answer.

Answer Source

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

from functools import reduce  # forward compatibility
import operator

reduce(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).


>>> import operator
>>> somelist = ['index0', ['index10', 'index11', ['index120', 'index121', ['index1220']]]]
>>> indices = [1, 2, 2, 0]
>>> reduce(operator.getitem, indices, somelist)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download