I need to create a function that takes a sequence of integers, indices
, with arbitrary length that will act as indices for a nested list, the_list
and update the value at the final index with a new value, new_val
. For example:
>>> the_list = [[1, 2], [3, 4], [5, 6]]
>>> indices = [2, 1]
>>> new_val = 'a'
>>> foo(the_list, indices, new_val)
[[1, 2], [3, 4],[5, 'a']]
This is equivalent to doing the_list[indices[0]][indices[1]] = new_val
but I need to be able to this for a list of any length.
If list indeces has lenght 5 and the_list only 2 then the function uses only 2 first elements from indices.
As mentioned in your edit, you Dont know indeces
. In this case:
def get_ind(a,ind):
if len(ind)==1:
return a[0]
return get_ind(a[ind[0]],ind[1:])
Some examples:
>>>a = [[["a", 15], [12, 0]], [[12, 4]]]
>>>indeces = [0,1,0]
>>>get_ind(a,indeces)
12
>>>a = [12, 4]
>>>indeces = [2]
>>>get_ind(a,indeces)
12
You can also use python exec in order to set/get the value:
>>>a = [[["a", 15], [12, 0]], [[12, 4]]]
>>>indeces = [0,1,0]
>>>newval = 217
>>>s = "a"+"".join(['['+str(x)+']'for x in indeces])+"="+str(newval )
>>>s
'a[0][1][0]=217'
>>>exec s
>>>a
[[["a", 15], [217, 0]], [[12, 4]]]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments