我有2個list分別為list1及list2, 想依序一一把list1的元素搬移到list2, 我寫了下
列程式碼:
list1 = []
list2 = []
list1.append("A")
list1.append("B")
list1.append("C")
list1.append("D")
list1.append("E")
list1.append("F")
print("Before:")
print("list1=", list1)
print("list2=", list2)
print("")
print("copying:")
for element in list1:
list2.append(element)
print("list2=", list2)
list1.remove(element)
print("list1=", list1)
print("")
print("After:")
print("list1=", list1)
print("list2=", list2)
輸出結果為:
Before:
list1= ['A', 'B', 'C', 'D', 'E', 'F']
list2= []
copying:
list2= ['A'] #1 : list2.append(element)
list1= ['B', 'C', 'D', 'E', 'F'] #2 : list1.remove(element)
list2= ['A', 'C'] #3 : list2.append(element)
list1= ['B', 'D', 'E', 'F'] #4 : list1.remove(element)
list2= ['A', 'C', 'E'] #5 : list2.append(element)
list1= ['B', 'D', 'F'] #6 : list1.remove(element)
After:
list1= ['B', 'D', 'F']
list2= ['A', 'C', 'E']
#1 把 "A" 加到 list2 與預期相同
#2 把 "A" 從 list1 移除與預期相同
不過#3為什麼是 "C" 被加到 list2 而不是 "B" 呢?