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']
上一篇: svg入门制作简易动画
下一篇: 使用HTML+CSS制作加载动画
推荐阅读
-
0x3 Python学习之路之Python列表copy
-
Python基础学习之基本数据结构详解【数字、字符串、列表、元组、集合、字典】
-
Python基础学习之基本数据结构详解【数字、字符串、列表、元组、集合、字典】
-
Python学习之路:通过分片的方式修改列表的技巧(拓展知识)
-
python入门学习笔记之操作列表
-
关于Python学习之 列表与字典
-
数据分析师养成之路之Python篇:从头学习机器学习之决策树(预)
-
Python新手学习基础之数据结构-列表3 删除 popcleardelremove
-
Python学习之路:通过分片的方式修改列表的技巧(拓展知识)
-
python学习之路 --(列表推导式的应用)