Sequential replacement of List values ​​with values ​​from another list

advertisements

Lets say I have a list:

my_list = ["A", "B", "C", "X", "X", "X"]

and I want to replace the X values with values from another list or in my case a 2D list(This list is generated with the repeat number being equal to the number of "X" in the list):

combinations = list(itertools.product('LE', repeat= 3))

so

combinations = [('L', 'L', 'L'), ('L', 'L', 'E'), ('L', 'E', 'L'), ('L', 'E', 'E'), ('E', 'L', 'L'), ('E', 'L', 'E'), ('E', 'E', 'L'), ('E', 'E', 'E')]

My question is how do I replace the "X" values in my_list with the values from combinations, such that the first result would be ["A", "B", "C", "L", "L", "L"] and the second result ["A", "B", "C", "L", "L", "E"] etc. Preferably I would like to put these into a 2D list which I could then print.

Edit: To clarify, my_list will be unknown and the "X" values may dispersed in an unknown fashion.


I might use:

def mergefill(to_fill, fill_char, fill_from):
    for filler in fill_from:
        it = iter(filler)
        yield [c if c != fill_char else next(it) for c in to_fill]

which gives

>>> my_list = ["A", "B", "C", "X", "X", "X"]
>>> list(mergefill(my_list, 'X', product('LE', repeat=3)))
[['A', 'B', 'C', 'L', 'L', 'L'], ['A', 'B', 'C', 'L', 'L', 'E'], ['A', 'B', 'C', 'L', 'E', 'L'], ['A', 'B', 'C', 'L', 'E', 'E'], ['A', 'B', 'C', 'E', 'L', 'L'], ['A', 'B', 'C', 'E', 'L', 'E'], ['A', 'B', 'C', 'E', 'E', 'L'], ['A', 'B', 'C', 'E', 'E', 'E']]

It also handles cases where the fill characters aren't contiguous:

>>> my_list = ["A", "X", "B", "X"]
>>> list(mergefill(my_list, 'X', product('LE', repeat=2)))
[['A', 'L', 'B', 'L'], ['A', 'L', 'B', 'E'], ['A', 'E', 'B', 'L'], ['A', 'E', 'B', 'E']]