Suppose I have a nested list (ndlist
) similar to an N-D array of arbitrary dimensions (let ndim
be the number of dimensions) and a tuple indexes
with len(indexes) == ndim
. If ndlist
was an N-D array I could do the following:
ndlist[indexes] = (some object)
What is the equivalent for a list? Note that ndim
is arbitrary so I can't hardcode it like this:
ndlist[indexes[0]][indexes[1]]... = (some object)
Here's an example for ndim == 3:
ndlist = [[[10, 10], [10, 10]],[[10, 10], [10, 10]]] % 3-D (2x2x2) list with all elements equal to 10
When I know ndim beforehand I can edit the (0,0,0) element of ndlist like this:
ndlist[0][0][0] = 11 %changing from 10 to 11 requires 3 [0]s in sequence
Now suppose ndims == 4 (4-dimensional list). Editing the the (0,0,0,0) element of ndlist would require something like this:
ndlist[0][0][0][0] = 11 %change to 11 requires 4 [0]s in sequence
And for arbitrary ndims:
ndlist[0][0][0]...[0] = 11 %change to 11 requires ndim [0]s in sequence
As you see, I can't index the list that way for the general case where ndim is not known in advance, as it requires to type as many [0] as ndim.
If instead of the list I had an array like this:
ndarray = np.array(ndlist)
Accessing the (0, 0, 0, ... ,0) would not be an issue since I can using a tuple to index all dimensions simultaneously like that:
% 3d case
indexes = (0,0,0)
ndarray[indexes]
% 4d case
indexes = (0,0,0,0)
ndarray[indexes]
% n-d case
indexes = (0, 0, 0, ... ,0) % I can generate this with code
ndarray[indexes] = 11
Is there a way to index a list with a single tuple like that? Even better, can the tuple hold slices instead of indexes? For instance arrays also allow this:
ndarray[0:2, 0, 0] = np.array([0, 0])
The only solution have found to my problem is to use recursion to index one dimension at a time. Is there a better solution? Thanks!