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

我想檢查數字 1 是否在所有嵌套列表的第三列中,如果是,則應將 1 替換為 0,將該列表中的 2 替換為 1。

提前致謝

請嘗試以下操作:

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

執行后, 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]]

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