python第二章(2)列表

names=["zhangyang","guyun","xiangpeng","leiming","xuliangchen"]
#查看
print(names[0],names[2])
print(names[0:2]) #切片:前两个
print(names[-1]) #从后面开始取
print(names[-3:-1]) #取出guyun,xiangpeng
print(names[-3:]) #后3个

#追加到最后
names.append("leihaidong")
#print(names)
#插入
names.insert(1,"leiming")
names.insert(3,"xinzhiyu")
print(names)
#改
names[2]="xiedi" #correct
print(names)
#删
#names.remove("leiming") #delete1
#names.pop(1) #delete2
print(names)

#显示某一项的位置
print(names.index('xiangpeng'))
#显示某一项出现的次数
print(names.count('leiming'))

#names.clear() #清空

#names.reverse() #反转
#names.sort() #排序,按照ascii码表排序

#扩展,后删除列表
names2=[1,2,3]
names.extend(names2)
del names2
print(names)


#浅copy
names=["zhangyang","guyun","xiangpeng",["alex","jack"],"leiming","xuliangchen"]

names3=names.copy() #第1种
'''
names3=copy.copy(names) #第2种,前面要加import copy
names3=names[:] #第3种,全切片
'''
print(names)
print(names3)
names2=names
names[2]="向鹏"
names[3][0]="Alex Angle"
names3[3][1]="JACK"
print(names)
print(names3)
print(names2)

#结果

['zhangyang', 'guyun', 'xiangpeng', ['alex', 'jack'], 'leiming', 'xuliangchen']
['zhangyang', 'guyun', 'xiangpeng', ['alex', 'jack'], 'leiming', 'xuliangchen']

['zhangyang', 'guyun', '向鹏', ['Alex Angle', 'JACK'], 'leiming', 'xuliangchen']
['zhangyang', 'guyun', 'xiangpeng', ['Alex Angle', 'JACK'], 'leiming', 'xuliangchen']

在复制时,第一层相当于重新copy了一份;而第二层相当于指针(无论改names还是names3的第二层,两个列表都发生改变)

['zhangyang', 'guyun', '向鹏', ['Alex Angle', 'JACK'], 'leiming', 'xuliangchen']

#深copy(一般不用)

import copy

names4=copy.deepcopy(names)

 

names[2]="向鹏"
names[3][0]="Alex Angle"
print(names4)

 

 

#结果
['zhangyang', 'guyun', 'xiangpeng', ['alex', 'jack'], 'leiming', 'xuliangchen']

#跳着打印
names=["zhangyang","guyun","xiangpeng","leiming","xuliangchen"]
print(names[0:-1:2])
print(names[::2])
#结果

['zhangyang', 'xiangpeng']
['zhangyang', 'xiangpeng', 'xuliangchen']

 

#浅copy示例(夫妻共有的银行账户)

person=["name",["saving",100]]

p1=person[:]
p2=person[:]

p1[0]='alex'
p2[0]='alice'

p1[1][1]-=70
print(p1)
print(p2)

#结果

['alex', ['saving', 30]]
['alice', ['saving', 30]]

 

posted @ 2018-01-14 21:44  cecelia  阅读(192)  评论(0编辑  收藏  举报