定义列表
1 names = ["Zhangyang", "Guyun", "Xiangpeng", "Xuliangchen"]
通过下标取列表中的值
1 print(names[0], names[2])
切片:取多个元素
1 print(names[1:3]) # 取第二个到第三个值 注:顾头不顾尾 2 3 print(names[0:3]) # 取第一个到第三个值 4 5 print(names[-1]) # 取最后一个值 6 7 print(names[-2]) # 取倒数第二个值 8 9 print(names[-3:-1]) # 取倒数第三个到倒数第二个值 注:从左往右取值 10 11 print(names[-2:]) # 取倒数第二个到倒数最后一个值 注:省略冒号后的值,取到最后一个 12 13 print(names[:3]) # 取第一个到第三个值 注:省略冒号前的值,从第一个开始取值 14 15 print(names[:])
追加元素
1 names.append("Leihaidong")
插入元素
1 names.insert(1, "Chenzhonghua") 2 names.insert(3, "Xinzhiyu")
修改元素
1 names[2] = "Xiedi"
删除元素
1 names.remove("Chenzhonghua") # 方法一 2 3 del names[1] # 方法二 4 5 names.pop() # 无下标,默认删除最后一个 6 7 names.pop(1) # 方法三
查找元素
1 print(names.index("Xiedi")) 2 3 print(names[names.index("Xiedi")])
统计元素
1 print(names.count("Chenzhonghua"))
清空列表
1 names.clear()
反转列表
1 names.reverse()
排序列表
1 names.sort()
扩展列表
names = ["Zhangyang", "Guyun", "Xiangpeng", "Chenzhonghua", "Xuliangchen"] names2 = [1, 2, 3, 4] names.extend(names2) print(names, names2)
删除列表
1 del names2
拷贝列表
1 names = ["Zhangyang", "Guyun", "Xiangpeng", "Chenzhonghua", "Xuliangchen"] 2 3 names2 = names.copy() 4 5 print(names) 6 7 print(names2)
拷贝列表为浅复制,只复制一层,深层指向内存地址
1 names = ["Zhangyang", "Guyun", "Xiangpeng", ["alex", "jack"], "Chenzhonghua", "Xuliangchen"] 2 3 names2 = names.copy() 4 5 names[2] = "向鹏" 6 7 names[3][0] = "ALEXANDER" 8 9 print(names) 10 11 print(names2)
如果列表赋值给列表,则只会指向内存地址,与字符串及数字赋值不同
1 names = ["Zhangyang", "Guyun", "Xiangpeng", ["alex", "jack"], "Chenzhonghua", "Xuliangchen"] 2 3 names2 = names 4 5 names[2] = "向鹏" 6 7 names[3][0] = "ALEXANDER" 8 9 print(names) 10 11 print(names2)
深层复制,导入copy模块
1 import copy 2 3 names = ["Zhangyang", "Guyun", "Xiangpeng", ["alex", "jack"], "Chenzhonghua", "Xuliangchen"] 4 5 names2 = copy.deepcopy(names) # 深Copy,ames2 = copy.copy(names) 为浅Copy 6 7 names[2] = "向鹏" 8 9 names[3][0] = "ALEXANDER" 10 11 print(names) 12 13 print(names2)
列表内元素的循环
1 names = ["Zhangyang", "Guyun", "Xiangpeng", ["alex", "jack"], "Chenzhonghua", "Xuliangchen"] 2 3 for i in names: 4 print(i)
跳跃切片
1 names = ["Zhangyang", "Guyun", "Xiangpeng", ["alex", "jack"], "Chenzhonghua", "Xuliangchen"] 2 3 print(names[0:-1:1]) # 从第一个值开始,到倒数第二个,每跳跃一个值切片
省略写法
1 names = ["Zhangyang", "Guyun", "Xiangpeng", ["alex", "jack"], "Chenzhonghua", "Xuliangchen"] 2 3 print(names[::2]) # 从第一个值开始,到最后一个,每跳跃一个值切片
1 names = ["Zhangyang", "Guyun", "Xiangpeng", ["alex", "jack"], "Chenzhonghua", "Xuliangchen"] 2 3 print(names[:]) # 从第一个值开始,到最后一个
浅Copy的三种方式
1 import copy 2 3 person = ['name', ['a', 100]] 4 5 p1 = copy.copy(person) 6 p2 = person[:] 7 p3 = list(person)
浅Copy的应用实例
1 import copy 2 3 person = ['name', ['saving', 100]] 4 5 p1 = person[:] 6 p2 = person[:] 7 8 p1[0] = 'husband' 9 p2[0] = 'wife' 10 11 p1[1][1]=50 12 13 print(p1) 14 print(p2)
元组
元组是存一组数,只是它一旦创建,便不能再修改,所以又叫只读列表
它有2个方法,一个是count,一个是index
1 names = ('jack', 'Alex')