Python 如何複製巢狀列表
本教程中,我們將瞭解在 Python 中複製巢狀列表的不同方法。我們逐個來看一下。
首先,我們將使用迴圈複製巢狀列表。這是最常見的方法。
示例
# initializing a list nested_list = [[1, 2], [3, 4], [5, 6, 7]] # empty list copy = [] for sub_list in nested_list: # temporary list temp = [] # iterating over the sub_list for element in sub_list: # appending the element to temp list temp.append(element) # appending the temp list to copy copy.append(temp) # printing the list print(copy)
輸出
如果你執行以上程式碼,你將獲得以下結果。
[[1, 2], [3, 4], [5, 6, 7]]
讓我們看看如何使用列表解析和解包運算子來複制巢狀列表。
示例
# initializing a list nested_list = [[1, 2], [3, 4], [5, 6, 7]] # copying copy = [[*sub_list] for sub_list in nested_list] # printing the copy print(copy)
輸出
如果你執行以上程式碼,你將獲得以下結果。
[[1, 2], [3, 4], [5, 6, 7]]
現在,我們瞭解另一種複製巢狀列表的方法。我們會有一個名為“deepcopy”的方法,該方法從“copy”模組中複製巢狀列表。我們來看一下。
示例
# importing the copy module import copy # initializing a list nested_list = [[1, 2], [3, 4], [5, 6, 7]] # copying copy = copy.deepcopy(nested_list) # printing the copy print(copy)
輸出
如果你執行以上程式碼,你將獲得以下結果。
[[1, 2], [3, 4], [5, 6, 7]]
結論
如果你對本教程有任何疑問,請在註釋部分提及。
廣告