Disclaimer:beginner, self-teaching Python user.
A pretty cool feature of ndarrays is their ability to accept a tuple of integers as indices (e.g.
myNDArray[(1,2)] == myNDArray
I'm interpreting your question as:
I have an N-dimensional list, and a tuple containing N values (T1, T2... TN). How can I use the tuple values to access the list? I don't know what N will be ahead of time.
I don't know of a built-in way to do this, but you can write a method that iteratively digs into the list until you reach the innermost value.
def get(seq, indices): for index in indices: seq = seq[index] return seq seq = [ [ ["a","b"], ["c","d"] ], [ ["e","f"], ["g","h"] ] ] indices = [0,1,0] print get(seq, indices)
You could also do this in one* line with
reduce, although it won't be very clear to the reader what you're trying to accomplish.
print reduce(lambda s, idx: s[idx], indices, seq)
(*if you're using 3.X, you'll need to import
functools. So, two lines.)
If you want to set values in the N-dimensional list, use
get to access the second-deepest level of the list, and assign to that.
def set(seq, indices, value): innermost_list = get(seq, indices[:-1]) innermost_list[indices[-1]] = value