Reputation: 42449
I'm looking for a general way to access elements in a list using indexes stored in another list.
For example, I have the list:
b = [[[[[0.2], [3]], [[4.5], [78]], [[1.3], [0.23]], [[6.], [9.15]]],
[[[3.1], [44]], [[1.], [66]], [[0.18], [2.3]], [[10], [7.5]]],
[[[3], [4.]], [[12.3], [12]], [[7.8], [3.7]], [[1.2], [2.1]]]]]
and I need to access the element whose index are stored in:
c = [0, 0, 0, 1, 0]
that is:
3
This won't work:
b[c[0]][c[1]][c[2]][c[3]][c[4]]
because the shape of b
changes with every run of my code, which is why I need a general way of using c
to access the element in b
.
Something like:
b[*c]
that I would've bet would work, but it doesn't.
Upvotes: 2
Views: 108
Reputation: 15433
You could use a recursive function. A recursive function is a function that calls itself. In this case, each time I call the function, I decrease the dimension of its two arguments.
b = [[[[[0.2], [3]], [[4.5], [78]], [[1.3], [0.23]], [[6.], [9.15]]],
[[[3.1], [44]], [[1.], [66]], [[0.18], [2.3]], [[10], [7.5]]],
[[[3], [4.]], [[12.3], [12]], [[7.8], [3.7]], [[1.2], [2.1]]]]]
c = [0, 0, 0, 1, 0]
def getitem(arr, indices):
if isinstance(indices, int):
return arr[indices]
if len(indices) == 1:
return arr[indices[0]]
item = indices[0]
new_indices = indices[1:]
return getitem(arr[item], new_indices)
print getitem(b, c) ## prints 3
Upvotes: 2
Reputation: 26427
Use reduce (or functools.reduce for forward-compatible with Python 3)
>>> def getitems(data, keys):
... return reduce(lambda a, b: a[b], [data]+keys)
...
>>> getitems(b, c)
3
This assumes that keys
is always a list.
Upvotes: 4