How to append/replace an item from multi dimensional array by an item from another multi-dimensional array based on a specific condition

Viewed 83

I have 2 3-d arrays and am trying to replace the innermost element of 1st with the elements of 2nd array. The code I wrote is -

my_list = [
           [['K', ['a', 'i'], '1'], ['W', ['b', 'y'], '1']], 
           [['T ', ['d', 'i', 'e', 'q', 'f', 'j'], '1'], ['P', ['d', 'r'], '1']]]

ref_list =  [['a', ['M', 'H'], 'b', ['L', 'M']], ['e', ['F'], 'd', ['M', 'N']]]
for a, b in zip(my_list , ref_list ):
    for i, subl in enumerate(a):
        for ii, v in enumerate(subl):
            if isinstance(v, list):
                new_subl=subl[ii]
                subl[ii]=[]
                for j in b[i]:
                    subl[ii] +=[j] + new_subl
                break

I am not getting the desired output. The output I am looking for is of sort (expected output)-

[[['K', ['M', 'i', 'H', 'i'], '1'], ['W', ['L', 'y', 'M', 'y'], '1']], [['T ', ['M', 'i', 'N', 'i', 'F', 'q', 'f', 'j'], '1'], ['P', ['M', 'r', 'N', 'r'], '1']]]

I want to replace the innermost element of my_list with the elements of the innermost list of ref_list if that element exists in ref_list. As a refrence, I want to replace ['a', 'i'] with ['M', 'i', 'H', 'i'] as they are followed by a in ['a', ['M', 'H'] and so on for the rest of the elements. Also if the element is not found in ref_list, I don't want to touch it. For eg - 'f' doesn't exist in ref_list so don't do anything with it.

1 Answers

You can use zip with collections.deque to track the replacements as you iterate over the innermost lists of my_list:

from collections import deque
def update(a, b):
   d = {b[i]:b[i+1] for i in range(0, len(b), 2)}
   for x, y, z in a:
      g, r = [], deque()
      for i in y[::-1]:
         if i not in d:
            r.appendleft(i)
         else:
            g = [l for k in d[i] for l in [k, *r]]+g
            r = deque()
      g = list(r)+g
      yield [x, list(g), z]

my_list = [[['K', ['a', 'i'], '1'], ['W', ['b', 'y'], '1']], [['T ', ['d', 'i', 'e', 'q', 'f', 'j'], '1'], ['P', ['d', 'r'], '1']]]
ref_list = [['a', ['M', 'H'], 'b', ['L', 'M']], ['e', ['F'], 'd', ['M', 'N']]]
result = [list(update(*i)) for i in zip(my_list , ref_list)]

Output:

[[['K', ['M', 'i', 'H', 'i'], '1'], ['W', ['L', 'y', 'M', 'y'], '1']], [['T ', ['M', 'i', 'N', 'i', 'F', 'q', 'f', 'j'], '1'], ['P', ['M', 'r', 'N', 'r'], '1']]]
Related