Python: Accessing elements of multi-dimensional list, given a list of indexes -


i have multidimensional list f, holding elements of type. so, if example rank 4, elements of f can accessed f[a][b][c][d].

given list l=[a,b,c,d], access f[a][b][c][d]. problem rank going changing, cannot have f[l[0]][l[1]][l[2]][l[3]].

ideally, able f[l] , element f[a][b][c][d]. think can done numpy, types of arrays i'm using, numpy not suitable, want python lists.

how can have above?

edit: specific example of i'm trying achieve, see demo in martijn's answer.

you can use reduce() function access consecutive elements:

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

in python 3 reduce moved functools module, in python 2.6 , can access in location.

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

demo:

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

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -