简体   繁体   中英

Transferring Values in nested dictionaries/lists

list = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], 
        [2, 3, 1, 0, 0], [3, 0, 1, 2, 0], [2, 0, 1, 3, 0]]

I would like to check if the number 1 is in the third column of all the nested lists, if it is than it should replace the 1 with a 0 and the 2 in that list with a 1.

Thanks in advance

Try the following:

nested_lists = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], 
                [2, 3, 1, 0, 0], [3, 0, 1, 2, 0], [2, 0, 1, 3, 0]]

for list_ in nested_lists:

    if list_[2] == 1:

        list_[2] = 0
        list_    = [1 if n == 2 else n for n in list_]

After execution, nested_lists goes from the given

[[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], 
 [2, 3, 1, 0, 0], [3, 0, 1, 2, 0], [2, 0, 1, 3, 0]]

To

[[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2]
 [1, 3, 0, 0, 0], [3, 0, 0, 1, 0], [1, 0, 0, 3, 0]]

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