Python: Replace element in list inside list of list, with value from another list in same

Issue

I have a list of lists in python in which I want to replace the first value of some lists with the first value of the list preceding it, but only for certain lists.

for i, x in enumerate(protected_rows):
        k = protected_rows[i + 1]
        dup_rows_indx = range(x + 2, k, 2) =
        for j in dup_rows_indx:
            try:
            rows[j][0] = rows[j-1][0]
            else:
            continue

basically if my list was

rows = [[a, b, c], [d], [e, f, g, h, i], [j, k, l, m], [n], [o, p], [q, r, s], [t, u], [v, w, x]]

and protected_rows = [1, 4] I want the output to be

rows = [[a, b, c], [d], [e, f, g, h, i], [e, k, l, m], [n], [o, p], [o, r, s], [t, u], [t, w, x]]

Any help appreciated. Relatedly I also then want to remove rows[j-1] but I’ve completely failed at the first step. Thank you.

Solution

Just for clarification here my view on the sample you’ve provided:

rows = [
    ['a', 'b', 'c'],
    ['d'],                      # < protected row (index: 1)
    ['e', 'f', 'g', 'h', 'i'],
    ['j', 'k', 'l', 'm'],
    ['n'],                      # < protected row (index: 4)
    ['o', 'p'],
    ['q', 'r', 's'],
    ['t', 'u'],
    ['v', 'w', 'x']
]

My assumption is that [2, 5] should be [1, 4]. (If you don’t want to adjust that then there’s an easy fix.)

Now try

protected_rows = [1, 4]
indices = [-1] + protected_rows + [len(rows)]
for i_0, i_1 in zip(indices[:-1], indices[1:]):
    for i in range(i_0 + 2, i_1, 2):
        rows[i][0] = rows[i - 1][0]

or (if you want to stick with [2, 5])

protected_rows = [2, 5]
indices = [-1] + [i - 1 for i in protected_rows] + [len(rows)]
for i_0, i_1 in zip(indices[:-1], indices[1:]):
    for i in range(i_0 + 2, i_1, 2):
        rows[i][0] = rows[i - 1][0]

to get

rows = [
    ['a', 'b', 'c'],
    ['d'],                      # < protected row (index: 1)
    ['e', 'f', 'g', 'h', 'i'],  
    ['e', 'k', 'l', 'm'],       # < first item now 'e'
    ['n'],                      # < protected row (index: 4)
    ['o', 'p'],
    ['o', 'r', 's'],            # < first item now 'o'
    ['t', 'u'],
    ['t', 'w', 'x']             # < first item now 't'
]

Is that what you are looking for?

Answered By – Timus

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.