Convert tuple into index for nested list

Viewed 188

I'm given coordinates for nested n-dimensional lists, in which I have to insert a certain value.

Something like (3,1,4) for a 3-D list or (3,1,4,1) for a 4-D list. The proper way to change this value would be:

mylist[3][1][4] = 'x'    
mylist[3][1][4][1]  = 'y'

It's easy to do this if I always know how many dimensions the list is, but I have to do this for any n. I'm also not allowed to import anything(lab assignment).Thanks!

3 Answers

This mylist[3][1][4][1] = thing is the same as this:

tmp = mylist[3][1][4]
tmp[1] = thing

You could use this fact like this:

def setitem(the_list, indices: tuple, value):
    try:
        index, = indices
    except ValueError:
        # there's more than one index - dig one dimension deeper
        setitem(the_list[indices[0]], indices[1:], value)
    else:
        # one index left - use it in assignment
        the_list[index] = value

Then call:

mylist[3][1][4][1]  = 'y'
setitem(mylist, (3, 1, 4, 1), 'y')

An assignment like mylist[3][1][4] = 'x' is really a chain of method calls in disguise.

mylist.__getitem__(3).__getitem__(1).__setitem__(4, 'x')

As such, you'll need a loop; all but the last index in your tuple will be used to get a reference to the list you are actually updating. The last index is used for the actual update.

idx = (3, 1, 4)

t = mylist
*dig, update = idx
for i in dig:  # (3, 1) are used for __getitem__
    t = t[i]
# t == mylist[3][1]
# t[4] = 'x' == t.__setitem__(4, 'x')
t[update] = 'x'

you could use a recursive approach:

def change_item(nested_list, indices, value):
    if len(indices) > 1:
        change_item(nested_list[indices[0]], indices[1:])

    else:
        nested_list[indices[0]] = value

change_item(mylist, (3,1,4), 'x')
Related