编写一个 Python 程序将一个列表克隆或复制到另一个列表。在此语言中,我们可以使用列表函数进行克隆或复制。
orgList = [10, 20, 40, 60, 70]
print("Original List Items = ", orgList)
print("Original List Datatype = ", type(orgList))
newList = list(orgList)
print("New List Items = ", newList)
print("New List Datatype = ", type(newList))

Python 程序克隆或复制列表
在此示例中,我们对列表进行切片,不包含开始和结束值,这最终会返回所有项。
orgList = [40, 60, 80, 100, 120]
print("Original Items = ", orgList)
newList = orgList[:]
print("New Items = ", newList)
Original Items = [40, 60, 80, 100, 120]
New Items = [40, 60, 80, 100, 120]
在此程序中,我们使用 extend 函数将列表复制到另一个列表。
orgList = [22, 33, 44, 55, 66, 77, 88, 99]
print("Original Items = ", orgList)
newList = []
newList.extend(orgList)
print("New Items = ", newList)
Original Items = [22, 33, 44, 55, 66, 77, 88, 99]
New Items = [22, 33, 44, 55, 66, 77, 88, 99]
此程序使用列表推导式来克隆或复制项。
orgList = [12, 23, 34, 45, 56, 67, 78]
print("Original Items = ", orgList)
newList = [lVal for lVal in orgList]
print("New Items = ", newList)
使用列表推导式复制的输出
Original Items = [12, 23, 34, 45, 56, 67, 78]
New Items = [12, 23, 34, 45, 56, 67, 78]
使用 for 循环克隆或复制列表的程序
我们使用 for 循环(for lVal in orgList)和 for 循环范围(for i in range(len(orgList)))来迭代列表项。在循环内部,append 函数将每个列表项添加到新列表中。
orgList = [25, 35, 45, 55, 65, 75, 85]
print("Original Items = ", orgList)
newList = []
for lVal in orgList:
newList.append(lVal)
print("New Items = ", newList)
newList2 = []
for i in range(len(orgList)):
newList2.append(orgList[i])
print("New Items = ", newList2)
Original Items = [25, 35, 45, 55, 65, 75, 85]
New Items = [25, 35, 45, 55, 65, 75, 85]
New Items = [25, 35, 45, 55, 65, 75, 85]
有一个内置的列表copy函数来复制或克隆列表项。
orgList = [24, 44, 54, 64, 76, 85]
print("Original Items = ", orgList)
newList = orgList.copy()
print("New Items = ", newList)
Original Items = [24, 44, 54, 64, 76, 85]
New Items = [24, 44, 54, 64, 76, 85]