How can a list of indices (called "indlst"), such as [[1,0], [3,1,2]] which corresponds to elements [1][0] and [3][1][2] of a given list (called "lst"), be used to access their respective elements? For example, given
indlst = [[1,0], [3,1,2]]
lst = ["a", ["b","c"], "d", ["e", ["f", "g", "h"]]]
(required output) = [lst[1][0],lst[3][1][2]]
The output should correspond to ["b","h"]. I have no idea where to start, let alone find an efficient way to do it (as I don't think parsing strings is the most pythonic
way to go about it).
EDIT:
I should mention that the nested level of the indices is variable, so while [1,0]
has two elements in it, [3,1,2]
has three, and so forth. (examples changed accordingly).
Recursion can grab arbitrary/deeply indexed items from nested lists:
I also found that arbitrary extra zero indices are fine:
So if you actually know the max nesting depth you can fill in the index list values by overwriting your (variable number, shorter) index list values into the max fixed length dictionary primed with zeros using the .update() dictonary method
Then directly hard code the indices of nested list, which ignores any "extra" hard coded zero valued indices
below hard coded 4 depth:
You can just iterate through and collect the value.
Or, you can use a simple list comprehension to form a list from those values.
Edit:
For variable length, you can do the following:
You can form a list with functions.reduce and list comprehension.
N.B. this is a python3 solution. For python2, you can just ignore the import statement.
you can try this code block: