python列表的学习笔记
列表的操作
第一个例子:
#names = "zhangyang guyun xiangpeng xuliangchen" #通过空格或逗号存变量
names = ["zhangyang","guyun","xiangpeng","xuliangchen"]
print(names[0],names[2])
print(names[1:3]) #切片
Print(names[-1]) #取最后一个值
print(names[-2:]) #取最后两个值
print(names[:3]) #取前三个值
第二个例子:
names = ["zhangyang","guyun","xiangpeng","xuliangchen"]
names.append("leihaidong") #增加一个leihaidong
names.insert(1,"chenronghua") #想插入到guyun的前面
names[2] = "xiedi" #想把guyun改成xiedi
names.remove("chenronghua") #想删掉chenronghua
de1 names[1] #想删掉chenronghua
names.pop() #删掉最后一个。如果没有输入下标则删掉最后一个
print(names.index("xiedi")) #找到xiedi的位置
print( names[names.index("xiedi")) #找到xiedi的位置并且把他打印出来
print(names.count("chenronghua")) #统计有多少个chenronghua
names.clear() #清空
names.reverse() #反转
names.sort() #排序
names.extend(names2) #合并
de1 names2#删掉变量
print(names)
第三个例子:
names = ["zhangyang","guyun","xiangpeng","xuliangchen"]
name2 = names.copy() #复制一份
print(names)
print(name2)
结果:
['zhangyang', 'guyun', 'xiangpeng', 'xuliangchen']
['zhangyang', 'guyun', 'xiangpeng', 'xuliangchen']
names[2] = "向鹏" #把xiangpeng改成中文
print(names)
print(names2)
结果:
['zhangyang', 'guyun', '向鹏', 'xuliangchen']
['zhangyang', 'guyun', 'xiangpeng', 'xuliangchen']
举例:copy子列表
深copy
import copy
names2 = copy.deepcopy()
列表循环:
names = ["zhangyang","guyun","xiangpeng",["emily","jack"],"xuliangchen"]
for i in names:
print(i)
结果:
zhangyang
guyun
xiangpeng
['emily', 'jack']
xuliangchen
循环切片:
三种方式:
name=copy.copy()
name[:]
list()