Accessing multidimensional lists with an index list

Kent Johnson kent37 at tds.net
Sun Apr 17 16:21:07 EDT 2005


Gabriel Birke wrote:
> Given the multidimensional list l:
> l = [ {'v1': 1, 'v2': 2},
> 	  [ {'v1':4, 'v2': 7},
> 	    {'v1': 9, 'v2': 86},
> 		[ {'v1': 77, 'v2': 88}]
> 	  ]
> 	 ]
> 
> I want to access specific items the indices of which are stored in
> another list. For now, I created a function to do this:
> 
> def getNestedValue(l, indices):
> 	while len(indices) > 0:
> 		i = indices.pop(0)
> 		l = l[i] #In future versions, put error checking here
> 	return l
> 
> Is there a more elegant or performant language construct to accomplish
> my task?

def getNestedValue(l, indices):
	for i in indices:
		l = l[i] #In future versions, put error checking here
	return l

Kent



More information about the Python-list mailing list