"" topic: Copy data from one list to another list. "" "" "" Import Copydef validate (A, B): "" "To verify the replication result:p Aram A::p Aram B:: Return:" "" Print ("a =", a) prin T ("b =", b) Print ("A = = B is", a = = b) print ("id (a) =", id (a)) print ("id (b) =", id (b)) a[0][0] = 0 print ("a [0] [0] = 0 after a = ", a) print (" a[0][0] = 0, B = ", b) a[0] = 1 print (" a[0 "= 1 after a =", a) print ("a[0] = 1, b =", b) def Answer1 (): "" "a= list B directly, then A and B are exactly the same, and a list changes when the B list changes: return:" "Print (" Output One: ") a = [[1, 2], [3, 4]] b = A validate (a, B) answer1 () def answer2 (): "" "Manually copy a layer: return:" "Print (" \ n output two: ") a = [[1, 2], [3, 4]] b = [] for i in A:b.append (i) validate (A, B) answer2 () def answer3 (): "" "Use the Copy method that comes with the list, but you can only copy one layer: return: "" "Print (" \ n output three: ") a = [[1, 2], [3, 4]] B = a.copy () validate (A, B) Answer3 () def answer4 ():" "" Take advantage of the list of slices: return: "" "Print (" \ n output four: ") a = [[1, 2], [3, 4]] B = a[:] Validate (A, B) answer4 () def ANSWER5 (): "" "Deep copy Copy.deepcopy:return:" "" Print ("\ n output five:") a = [[1, 2], [3, 4]] B = Copy.dee Pcopy (a) validate (a, B) Answer5 () def ANSWER6 (): "" "Shallow copy copy.copy, with Answer3:return:" "" Print ("\ n output six:") A = [[1, 2], [3, 4]] B = copy.copy (a) validate (a, B) Answer6 () def answer7 (): "" "Use list generation using a list of for processing, as if the generator : Return: "" "Print (" \ n output Seven: ") a = [[1, 2], [3, 4]] B = [I for i in a] validate (A, B) Answer7 () def answer8 ( ): "" Multiplies the list multiplied by one to generate the sequence of multiplication: [1,2,3]+[4,5,6]=[1,2,3,4,5,6] The sum of the columns is the concatenated [1,2,3]*3=[1,2,3,1,2,3,1,2,3] sequence multiplied by A constant n is the copy of the sequence n times [1,2,3]*[1,2,3]=[] Error Typeerror:return: "" "Print (" \ n output eight: ") a = [[1, 2], [3, 4]] B = A * 1 Validate (A, B) Answer8 () def answer9 (): "" "Table 1 expands to table 2: return:" "" Print ("\ n output nine:") a = [[1, 2], [3, 4 ]] B = [] B.extend (a) validate (a, B) Answer9 ()
Python Learning-Exercises (7)