第二周 第八节 列表的使用

深copy 浅copy 循环 步长切片

name=["zhangyang","guyun","guyun","xiangpeng","xia"]
name2=name.copy()

name[3]="向鹏"
print(name)
print(name2)

从上到下是有执行顺序的

['zhangyang', 'guyun', 'guyun', '向鹏', 'xia']
['zhangyang', 'guyun', 'guyun', 'xiangpeng', 'xia']

  

 

 

name=["zhangyang","guyun","xiangpeng",["alex,jack"],"xia"]
name2=name.copy()
name[2]="向鹏"
name[3][0]="ALEX" 
print(name)
print(name2)
这个copy是浅copy

['zhangyang', 'guyun', '向鹏', ['ALEX'], 'xia']
['zhangyang', 'guyun', 'xiangpeng', ['ALEX'], 'xia']

 

  

 


列表:
a=[1,2,3]
b=a
a[1]=555
b=[1,555,3] //注意这里b不在是等于[1,2,3]

 

 

a=[1,2,3]
b=a
a[1]=555
print(a)
print(b)

[1, 555, 3]
[1, 555, 3]

 

  


深copy,这时候的输出结果是完全两份不同的数据,互补干扰

import copy
name=["zhangyang","guyun","xiangpeng",["alex,jack"],"xia"]
name2=copy.deepcopy(name)
name[2]="向鹏"
name[3][0]="ALEX" 
print(name)
print(name2)
这个copy是浅copy

['zhangyang', 'guyun', '向鹏', ['ALEX'], 'xia']
['zhangyang', 'guyun', 'xiangpeng', ['alex,jack'], 'xia']

 

  

 

报名字的循环

name=["zhangyang","guyun","xiangpeng",["alex,jack"],"xia"]
for i in name:
print(i)



zhangyang
guyun
xiangpeng
['alex,jack']
xia

  

 

从第0个开始到第最后一个,跳一个显示一个
name=["zhangyang","guyun","xiangpeng",["alex,jack"],"xia"]
print(name[0:-1:2])


['zhangyang', 'xiangpeng']

  

 

0和-1可以省略掉
name=["zhangyang","guyun","xiangpeng","alex","xia"]
print(name[::2])
['zhangyang', 'xiangpeng', 'xia']

  

 

从0到-1全部打印,因为0 和-1可以省略掉
name=["zhangyang","guyun","xiangpeng",["alex,jack"],"xia"]
print(name[:])


['zhangyang', 'guyun', 'xiangpeng', ['alex,jack'], 'xia']

  

 

 


copy是对原内容的引用
person=['name',['a',100]]
p1=copy.copy(person)
p2=person[:]
p3=list(person)

 

 


person=['name',['a',100]]
p1=person[:]
p2=person[:]
print(p1)
print(p2)

 

['name', ['a', 100]]
['name', ['a', 100]]

 


浅 copy:创建联合账号
person=['name',['saving',100]]
p1=person[:]
p2=person[:]
p1[0]="Alex"
p2[0]="fengjie"

print(p1)
print(p2)

 

['Alex', ['saving', 100]]
['fengjie', ['saving', 100]]

 

 

两个人的联合账号都有100元
person=['name',['saving',100]]
p1=person[:]
p2=person[:]
p1[0]="Alex"
p2[0]="fengjie"
p1[1][1]=30 //变成30元,这时用的是浅copy
print(p1)
print(p2)

 


['Alex', ['saving', 30]]
['fengjie', ['saving', 30]]

posted on 2019-04-14 12:31  googleWang  阅读(110)  评论(0编辑  收藏  举报

导航