Search code examples
pythonlisthierarchyindices

placing a list with indices (changing length) after a hierarchy of lists to change the values


I have the following hierarchy of lists:

boundaries = [[0, 1, 2, 3, 4], [[5, 6, 7, 8, 9], [[0, 4, 8, 7], [4, 3, 9, 8]]],
              [[2, 1, 6, 5]], [[1, 0, 7, 6]]]

Two lists with indices:

index1 = [1, 0, 2]      # is the same as [1][0][2]  
index2 = [1, 1, 0, 1]   # is the same as [1][1][0][1]

However, when I try to do the description below, it does not work.

boundaries[index1] = 45  
boundaries[index2] = 45 

This is not possible, because index1 and index2 are lists.

How can I solve this?


Solution

  • This is probably a bad design .... but ... you could iteratively descend into your sublists like so:

    boundaries = [[0, 1, 2, 3, 4], [[5, 6, 7, 8, 9], [[0, 4, 8, 7], [4, 3, 9, 8]]],
                  [[2, 1, 6, 5]], [[1, 0, 7, 6]]] 
    
    index1 = [1, 0, 2]      # is the same as [1][0][2]  
    index2 = [1, 1, 0, 1]   # is the same as [1][1][0][1]
    
    
    def iterateively_descent(idx, l, val):
        # iteratively descent until the last sublist
        for k in idx[:-1]:
            l = l[k] 
        # set the value of the last sublist
        l[idx[-1]] = val
    
    print(boundaries)
    
    iterateively_descent(index1,boundaries,45)
    print(boundaries)
    
    iterateively_descent(index2,boundaries,145)
    print(boundaries)
    

    Output:

    [[0, 1, 2, 3, 4], [[5, 6, 7, 8, 9], [[0, 4, 8, 7], [4, 3, 9, 8]]],
     [[2, 1, 6, 5]], [[1, 0, 7, 6]]]
    
    [[0, 1, 2, 3, 4], [[5, 6, 45, 8, 9], [[0, 4, 8, 7], [4, 3, 9, 8]]],
     [[2, 1, 6, 5]], [[1, 0, 7, 6]]]
    
    [[0, 1, 2, 3, 4], [[5, 6, 45, 8, 9], [[0, 145, 8, 7], [4, 3, 9, 8]]], 
     [[2, 1, 6, 5]], [[1, 0, 7, 6]]]