birdseyeassassin
birdseyeassassin

Reputation: 41

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

Upvotes: 1

Views: 51

Answers (1)

Erick Shepherd
Erick Shepherd

Reputation: 1443

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

Upvotes: 1

Related Questions