0x3 Python list copy on the way to Python learning

Understanding copy

import copy

names = ["China", "ShanDong", "LiaoCheng", "University"]
names2 = names.copy()
print(names)
print(names2)
#['China', 'ShanDong', 'LiaoCheng', 'University']
#['China', 'ShanDong', 'LiaoCheng', 'University']

Modify the list information and recognize copy

import copy
names = ["China", "ShanDong", "LiaoCheng", "University"]
names2 = names.copy()
names[2] = "DongChang"
print(names,names2)
#['China', 'ShanDong', 'DongChang', 'University'] ['China', 'ShanDong', 'LiaoCheng', 'University']
Shallow copy
names = ["China", "ShanDong", "LiaoCheng",["GJHe","ymxowgk"] ,"University"]
names2 = names.copy()
names[2] = "DongChang"
print(names)
print(names2)
#['China', 'ShanDong', 'DongChang', ['GJHe', 'ymxowgk'], 'University'] ['China', 'ShanDong', 'LiaoCheng', ['GJHe', 'ymxowgk'], 'University']
#Memory address of the copy
There are three ways of shallow copy:

person = ['name',['money',100]]
p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)
Shallow copy application

Create a joint account. For example, Zhang San and Ma Rong are a couple. They have a common bank account. When Zhang San withdraws money, Ma Rong's account changes
person = ['name',['money',100]]
p1 = person[:]
p2 = person[:]

p1[0] = "Zhang San"
p2[0] = "Mayon"

p1[1][1] = 50

print(p1)
print(p2)
#output
#['Zhang San', 'money', 50]]
#['Ma Rong', 'money', 50]]


String, list assignment update difference
#Character string
a = 1;
b = a;
a = 2;
print("a:",a,"b:",b)
#a: 2 b: 1


#list
a = [1,2,4]
b = a
a[1] = 3333
print("a:",a,"b:",b)
#a: [1, 3333, 4] b: [1, 3333, 4]

Deep copy

names = ["China", "ShanDong", "LiaoCheng",["GJHe","ymxowgk"] ,"University"]
names2 = copy.deepcopy(names)
print(names)
print(names2)
names[2] = "DongChang"
names[3][0] = "gaojihe"
print(names)
print(names2)

#['China', 'ShanDong', 'LiaoCheng', ['GJHe', 'ymxowgk'], 'University']
#['China', 'ShanDong', 'LiaoCheng', ['GJHe', 'ymxowgk'], 'University']
#['China', 'ShanDong', 'DongChang', ['gaojihe', 'ymxowgk'], 'University']
#['China', 'ShanDong', 'LiaoCheng', ['GJHe', 'ymxowgk'], 'University']
#In this way, the value of the sublist will not be changed by copying, because deepcopy copies the sublist
 #Note: however, the deep copy method, if the data is large, full copy is to store two copies of data, occupy memory, use with caution!

Traversal list elements

names = ["China", "ShanDong", "LiaoCheng", "University"]
for i in names :
    print(i)


#output
China
ShanDong
LiaoCheng
University

List skipping slice

names = ["China", "ShanDong", "LiaoCheng", "University"]


print(names[0:-1:2])#[::2]

#['China', 'LiaoCheng']

 

Posted on Sun, 05 Jan 2020 17:40:13 -0800 by dhimok