python 正確復制list,克隆list 的各種方案


推薦4種方法

---------------------------------------------------------------

方法一:extend

L = [1, 2, 3]

List_1 = []
List_1.extend(L)

print('List_1 =', List_1)

解釋:新建一個空List,然后將L中所有的元素用extend的方法放入List_1中

 

 

方法二:切片

L = [1, 2, 3]

List_2 = L[:]

print('List_2 =', List_2)

解釋:取L的切片,然后賦值給List_2即可

 

 

方法三:拆包(*)

L = [1, 2, 3]

List_3 = [*L]

print('List_3 =', List_3)

解釋:將L中的元素拆分,然后放入一個list中,再然后賦值給List_3

 

 

方法四:用乘法

L = [1, 2, 3]

List_4 = L * 1

print('List_4 =', List_4)

解釋:數字1就是將L中的元素重復顯示1次

 

 

其他方法的話,並不是太推薦,因為效率不高

---------------------------------------------------------------

比如大家喜聞樂見的append方法,效率低下(不推薦)

L = [1, 2, 3]

List_5 = []
for e in L:
    List_5.append(e)

print('List_5 =', List_5)

 

 

或者更加pythonic的列表推導(可以用,顯得高大上)

L = [1, 2, 3]

List_6 = [e for e in L]
print('List_6 =', List_6)

 

 

又或者引入標准庫中的模塊(沒必要引入模塊)

from copy import deepcopy

L = [1, 2, 3]

List_7 = deepcopy(L)

print('List_7 =', List_7)

 

 

當然,重新用list進行封裝也可以(這種做法還可以)

L = [1, 2, 3]

List_8 = list(L)

print('List_8 =', List_8)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM