简体   繁体   English

在嵌套字典/列表中传输值

[英]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.我想检查数字 1 是否在所有嵌套列表的第三列中,如果是,则应将 1 替换为 0,将该列表中的 2 替换为 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执行后, 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]]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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