Home > Enterprise >  How to replace first instance of a value in a list which consits of multiple groups?
How to replace first instance of a value in a list which consits of multiple groups?

Time:07-18

I have 2 lists and I want to change the elements of 2nd list based on groups of 1st list. Example I have:-

a=[1,1,1,2,2,2,2,3,3,3,4,4,4]
b=['','','l2','','','','','','l3','l5','','l4','']

Both the lists have same number of elements. For every group of elements in 'a' list I only want to replace the value in list b at same index where the groups of elements are present in list a.

Conditions:- Only replace the value in list b if the element at that index(of list a) is empty or ''.

If the value is replaced once for a group don't replace the values of list b for the following elements of same group in list a.

If the list b has already some value present at same index don't replace it let it stay the same instead replace for the next empty one.

For example:- a=[1,1,1,1] and b=['l2' , '' , 'l3' ,''] then expect output for b is b=['l2','value','l3','']

Expected Output:

b=['value','','l2','value','','','','value','l3','l5','value','l4','']

My approach:-

a=[1,1,1,2,2,2,2,3,3,3,4,4,4]
b=['','','l2','','','','','','l3','l5','','l4','']
empty=''
xw=set()
for i in a:
    for j,k in enumerate(b):
        if i not in xw and k==empty:
            b[j]='value'
            xw.add(i)
        elif i in xw and k==empty:
            b[j]=empty
        else:
            pass
    pass
b

Output that I'm getting

['value',
 'value',
 'l2',
 'value',
 'value',
 '',
 '',
 '',
 'l3',
 'l5',
 '',
 'l4',
 '']

CodePudding user response:

Maybe you could use groupby and some fancy indexing where you search for the first empty string in each chunk to achieve this:

a=[1,1,1,2,2,2,2,3,3,3,4,4,4]
b=['','','l2','','','','','','l3','l5','','l4','']

from itertools import groupby
g = groupby(a)

i = 0
for group,data in g:
    n = len(list(data))
    b[b[i:i n].index('') i] = group
    i =n

print(b)

Output

[1, '', 'l2', 2, '', '', '', 3, 'l3', 'l5', 4, 'l4', '']

CodePudding user response:

Another solution (using assignment operator := - Python 3.8 feature):

from itertools import groupby

a = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4]
b = ["", "", "l2", "", "", "", "", "", "l3", "l5", "", "l4", ""]

out = []
for _, g in groupby(zip(a, b), lambda k: k[0]):
    val = None
    out.extend((val := "value") if v == "" and val is None else v for _, v in g)

print(out)

Prints:

['value', '', 'l2', 'value', '', '', '', 'value', 'l3', 'l5', 'value', 'l4', '']
  • Related