Skip to content Skip to sidebar Skip to footer

How To Append/replace An Item From Multi Dimensional Array By An Item From Another Multi-dimensional Array Based On A Specific Condition

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'

Solution 1:

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']]]

Post a Comment for "How To Append/replace An Item From Multi Dimensional Array By An Item From Another Multi-dimensional Array Based On A Specific Condition"