#範例5-7:串列/數組/列表,list的複製 #https://www.w3schools.com/python/python_lists_copy.asp #https://www.w3school.com.cn/python/ref_list_copy.asp #注意1:不可以直接設定list2 = list1, You cannot copy a list simply by typing list2 = list1, #原因:because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. #結果:改了list2, 也會更動到list1 #解決方法:There are ways to make a copy, one way is to use the built-in List method copy(). #語法:list2 = list1.copy() #語法:list2 = list(list1) #----------------------------- #1.錯誤的複製方法 a1 = ["tom","john","bo","mikewang","jolin","peter"] #結論:複製list,不可以直接 a2 = a1 #因為,兩個會連動,修改一個,就會改到另外一個 #---------------------------- #2.正確的複製方法(1) a1 = ["tom","john","bo","mikewang","jolin","peter"] #----------------------------- #3.正確的複製方法(2) a1 = ["tom","john","bo","mikewang","jolin","peter"] #-------------------------------------------------- #----------------------------------------------------------- #範例5-7:串列/數組/列表,list的複製 #https://www.w3schools.com/python/python_lists_copy.asp #https://www.w3school.com.cn/python/ref_list_copy.asp #注意1:不可以直接設定list2 = list1, You cannot copy a list simply by typing list2 = list1, #原因:because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. #結果:改了list2, 也會更動到list1 #解決方法:There are ways to make a copy, one way is to use the built-in List method copy(). #語法:list2 = list1.copy() #語法:list2 = list(list1) #1.錯誤的複製方法 a1 = ["tom","john","bo","mikewang","jolin","peter"] a2 = a1 a2[0] = "top" print(a1) print(a2) #結論:複製list,不可以直接 a2 = a1 #因為,兩個會連動,修改一個,就會改到另外一個 #2.正確的複製方法(1) a1 = ["tom","john","bo","mikewang","jolin","peter"] a3 = a1.copy() a3[0] = "ttt" print(a3) print(a1) #3.正確的複製方法(2) a1 = ["tom","john","bo","mikewang","jolin","peter"] a4 = list(a1) a4[0] = "aaa" print(a4) print(a1) #-----------------------------------------------------------