1 a=[‘zhao‘,‘qian‘,‘sun‘,‘li‘,‘zhou‘,‘‘] 2 3 #增删改查 4 #查 切片 [] 5 print(a[1:])#取到最后 6 print(a[1:-1])#取到倒数第二值 7 print(a[1:-1:1])#从左到右一个一个去取 8 print(a[1::2])#从左到右隔一个去取 9 print(a[3::-1]) 10 b=a[3::-1] 11 print(b)#[‘sanpang‘, ‘xiaohu‘, ‘jinxin‘, ‘wuchao‘] 12 print(a[-2::-1]) 13 print(a[1:-1:-2])
结果:
[‘qian‘, ‘sun‘, ‘li‘, ‘zhou‘, ‘wu‘] #5 [‘qian‘, ‘sun‘, ‘li‘, ‘zhou‘] #6 [‘qian‘, ‘sun‘, ‘li‘, ‘zhou‘] #7 [‘qian‘, ‘li‘, ‘wu‘] #8 [‘li‘, ‘sun‘, ‘qian‘, ‘zhao‘] #9 [‘li‘, ‘sun‘, ‘qian‘, ‘zhao‘] #11 [‘zhou‘, ‘li‘, ‘sun‘, ‘qian‘, ‘zhao‘] #12 [] #13
1 a=[‘zhao‘,‘qian‘,‘sun‘,‘li‘,‘zhou‘,‘wu‘] 2 3 #添加 append insert 4 5 a.append(‘xuepeng‘) #默认插到最后一个位置 6 print(a) 7 a.insert(1,‘xuepeng‘) #将数据插入到任意一个位置 8 print(a)
结果:
[‘zhao‘, ‘qian‘, ‘sun‘, ‘li‘, ‘zhou‘, ‘wu‘, ‘xuepeng‘] [‘zhao‘, ‘xuepeng‘, ‘qian‘, ‘sun‘, ‘li‘, ‘zhou‘, ‘wu‘, ‘xuepeng‘]
1 a=[‘zhao‘,‘qian‘,‘sun‘,‘li‘,‘zhou‘,‘wu‘] 2 #修改 3 # 4 a[1]=‘haidilao‘ 5 print(a) 6 a[1:3]=[‘a‘,‘b‘] 7 print(a)
结果
1 [‘zhao‘, ‘haidilao‘, ‘sun‘, ‘li‘, ‘zhou‘, ‘wu‘] 2 [‘zhao‘, ‘a‘, ‘b‘, ‘li‘, ‘zhou‘, ‘wu‘]
1 #删除 remove pop del 2 a=[‘zhao‘,‘qian‘,‘sun‘,‘li‘,‘zhou‘,‘wu‘] 3 a.remove(a[0]) 4 print(a) 5 b=a.pop(1) 6 print(a) 7 print(b) 8 del a[0] 9 print(a)
结果:
1 [‘qian‘, ‘sun‘, ‘li‘, ‘zhou‘, ‘wu‘] 2 [‘qian‘, ‘li‘, ‘zhou‘, ‘wu‘] 3 sun 4 [‘li‘, ‘zhou‘, ‘wu‘]
1 #count:计算某元素出现次数 2 t=[‘to‘, ‘be‘, ‘or‘, ‘not‘, ‘to‘, ‘be‘].count(‘to‘) 3 print(t) 4 5 #extend 6 a = [1, 2, 3] 7 b = [4, 5, 6] 8 a.extend(b) 9 print(a) 10 print(b)
1 2
2 [1, 2, 3, 4, 5, 6]
3 [4, 5, 6]
总结:
1 列表,元组 2 查 3 索引(下标) ,都是从0开始 4 切片 5 .count 查某个元素的出现次数 6 .index 根据内容找其对应的位置 7 "haidilao ge" in a 8 增加 9 a.append() 追加 10 a.insert(index, "内容") 11 a.extend 扩展 12 13 修改 14 a[index] = "新的值" 15 a[start:end] = [a,b,c] 16 17 删除 18 remove("内容") 19 pop(index) 20 del a, del a[index] 21 a.clear() 清空 22 23 排序 24 sort () 25 reverse()