欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

0x3 Python学习之路之Python列表copy

程序员文章站 2024-01-17 22:06:58
...

初认识copy

import copy

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

修改列表信息,认识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']
浅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']
#拷贝的内存地址
浅copy的三种方式:

person = ['name',['money',100]]
p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)
浅copy应用

创建联合账号,例如张三和马荣是一对夫妻关系,他俩有个共同银行账户,当张三取钱时,马荣账户跟随改变
person = ['name',['money',100]]
p1 = person[:]
p2 = person[:]

p1[0] = "张三"
p2[0] = "马荣"

p1[1][1] = 50

print(p1)
print(p2)
#输出
#['张三', ['money', 50]]
#['马荣', ['money', 50]]

字符串,列表赋值更新区别
#字符串
a = 1;
b = a;
a = 2;
print("a:",a,"b:",b)
#a: 2 b: 1


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

深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']
#这样复制就不会改变子列表的值了,是因为deepcopy将子列表也复制了一份
#注:不过,deepcopy方法,如果数据很大,完全复制就是存储两份数据,占用内存,慎用!

遍历列表元素

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


#输出
China
ShanDong
LiaoCheng
University

列表跳着切片

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


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

#['China', 'LiaoCheng']

 

相关标签: copy