列表的切片:
1 names=["汤姆","月寒","张梦","刘小小","郭靖","王瑞"] 2 3 print(names) 4 print(names[0]) 5 print(names[0],names[1]) 6 print(names[1:3]) #切取从下标1到3(不包括3)的元素 7 print(names[-1]) # 负数表示从后面开始取 8 print(names[-1:-3]) 9 print(names[-3:-1])#切片是从左往右开始取的 10 print(names[-2:]) #从该位置取到最后一个 11 print(names[0:-1:2]) #跳着切片 12 print(names[::2]) #跳着切片 从起始到结束位置可以省略
列表的插入和追加
1 names=["汤姆","月寒","张梦","刘小小","郭靖","王瑞"] 2 names.append("张三") #末尾追加 3 names.insert(1,"李四") #指定位置插入
列表的查找:
1 names=["汤姆","月寒","张梦","刘小小","郭靖","王瑞"] 2 print(names.index("汤姆")) # 查找变量位置,返回第一个下标 3 #print(names.index("杰克")) # 查找的不存在,异常错误 4 print(names.rindex("汤姆")) #rindex查找,返回最后一个的下标 5 print(names.index("汤姆",0,3)) 6 print(names[names.index("汤姆")]) #输出位置变量 7 print(names.find("张梦",0,4)) #find返回第一个 ,头部开始查找 可以指定位置查找 8 print(names.rfind("张梦")) #rfind返回最后一个,尾部开始查找 可以指定位置查找
列表的删除:
1 names=["汤姆","月寒","张梦","刘小小","郭靖","王瑞"] 2 names.remove("月寒") #删除 3 del names[3] #位置删除 4 names.pop() # 默认删除最后一个 5 names.pop(1) #等价于del下标删除 6 print(names)
列表修改、反转、清空、排序、扩展:
1 names=["汤姆","月寒","张梦","刘小小","郭靖","王瑞","月寒”] #列表 2 names[2]="张三"#修改 3 print(names.count("月寒")) #统计列表有多少个相同变量 4 names.reverse() # 列表反转 5 names.sort()# 排序 ,优先级从大到小( 特殊符号,数字,大写字母,小写字母) 6 names.clear(); # 列表清空 7 8 names2=["小明","李四"] 9 names.extend(names2) #合并列表,names2列表依然存在
列表嵌套:
mylist1=[1,2,3,["a","b","c"]] mylist2=[4,5,6] mylist3=[7,8,9] mylist=[mylist1,mylist2,mylist3] print(mylist) for data in mylist: for idata in data: print(idata) #三维嵌套 mylist=[ [ [1,2],[3,4] ], [ [5,6],[7,8] ], [ [9,10],[11,12] ]] for data1 in mylist: print(data1) for data2 in data1: print(data2) for data3 in data2: print(data3) #下标循环 for i in range(len(mylist)): #print(mylist[i]) for j in range(len(mylist[i])): #print(mylist[i][j]) for k in range(len(mylist[i][j])): print(mylist[i][j][k])