Python|如何复制嵌套列表
在上一篇文章中,我们已经了解了如何克隆或复制列表,现在让我们看看如何在Python中复制嵌套列表。
方法#1:使用迭代
# Python program to copy a nested list
# List initialization
Input_list = [[0, 1, 2], [3, 4, 5], ]
Output = []
# Using iteration to assign values
for x in range(len(Input_list)):
temp = []
for elem in Input_list[x]:
temp.append(elem)
Output.append(temp)
# Printing Output
print("Initial list is:")
print(Input_list)
print("New assigned list is")
print(Output)
输出:
Initial list is:
[[0, 1, 2], [3, 4, 5]]
New assigned list is
[[0, 1, 2], [3, 4, 5]]
方法 #2:使用 deepcopy
# Python program to copy a nested list
import copy
# List initialization
Input = [[1, 0, 1], [1, 0, 1]]
# using deepcopy
Output = copy.deepcopy(Input)
# Printing
print("Initial list is:")
print(Input)
print("New assigned list is")
print(Output)
输出:
Initial list is:
[[1, 0, 1], [1, 0, 1]]
New assigned list is
[[1, 0, 1], [1, 0, 1]]
方法#3:使用列表理解和切片
# Python program to copy a nested list
# List initialization
Input_list = [[0,1,2], [3,4,5], [0, 1, 8]]
# comprehensive method
out_list = [ele[:] for ele in Input_list]
# Printing Output
print("Initial list is:")
print(Input_list)
print("New assigned list is")
print(out_list)
输出:
Initial list is:
[[0, 1, 2], [3, 4, 5], [0, 1, 8]]
New assigned list is
[[0, 1, 2], [3, 4, 5], [0, 1, 8]]