简体   繁体   中英

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

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.

Original Code:

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

Edit As per Comment- See Below

If, on the other hand, you want to filter alterable lists based on a list of protected indices, then it can be done simply like this:

import copy

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

protected_rows= [2,4]

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

#start counting from 1, include final index
for i in range(1,len(lst)):
    if(i not in protected_rows ):
        lst2[i][0]=lst2[i-1][0]
        
print(lst) 
#print(protected_rows)
print(lst2)  
#out:
# [[1, 2, 3], [4, 5, 6], [7], [8, 9, 10], [11, 12, 13], [14, 15]]
# [[1, 2, 3], [1, 5, 6], [7], [7, 9, 10], [11, 12, 13], [11, 15]] 

Note: If we don't use a copy, the changes will cascade, ie the elements will be replaced by the altered value in previous list.

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?

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.

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM