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

Time:04-20

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 = [2, 5] 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.

CodePudding user response:

The code is not reproducible, so I am making an example as I go. Suppose we have a list of lists of integers, and we want to replace the first element of each list with the first element of its predecessor, but only if the replacement candidate is an even number. Here's one way of doing this:

import copy

lst = [[1,2,3],[4,5,6],[7],[8,9,10],[11,12,13],[14,15]]

#create a copy to change. 
lst2=copy.deepcopy(lst)
lst2

#iterate over both lists
for l,k in zip(lst, lst2[1:]):
    #print (l,k)

    if(k[0]%2==0):
        k[0]=l[0]

print('====')
print(lst2)

# Out:
# [[1, 2, 3], [1, 5, 6], [7], [7, 9, 10], [11, 12, 13], [11, 15]]

CodePudding user response:

You can try this:

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

protected_rows = [2, 5]

for i in range(len(rows)):
    for j in range(len(protected_rows)):
        if i == protected_rows[j]:
            rows[i 1][0] = rows[i][0]

for the rows[j-1] part please explain in more detail what you need.

  • Related