1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #Author:SKING
4 #python3列表操作大全 列表操作方法详解
5
6 #创建列表
7 list = ['a', 'b', 'c', 'd', 'e', 'f']
8 #取出列表
9 print(list[0], list[5]) #a f
10 #列表切片
11 print(list[1:3]) #['b', 'c']
12 print(list[-3:-1]) #['d', 'e']
13 #取的时候始终都是按照从左到右的顺序进行切片,动作都是顾头不顾尾。
14
15 #添加列表元素
16 #在最后面添加列表元素
17 list.append('g')
18 print(list) #['a', 'b', 'c', 'd', 'e', 'f', 'g']
19 #在任意位置插入列表元素
20 list.insert(1, 'b1')
21 print(list) #['a', 'b1', 'b', 'c', 'd', 'e', 'f', 'g']
22 #修改列表中的元素
23 list[1] = 'b2'
24 print(list) #['a', 'b2', 'b', 'c', 'd', 'e', 'f', 'g']
25 #删除列表中的元素
26 #方法1 删除指定位置
27 list.remove('b2')
28 print(list) #['a', 'b', 'c', 'd', 'e', 'f', 'g']
29 #方法2 删除指定位置
30 del list[1]
31 print(list) #['a', 'c', 'd', 'e', 'f', 'g']
32 #方法3
33 return_result = list.pop()
34 print(list) #['a', 'c', 'd', 'e', 'f']
35 #pop()方法是删除最后一个元素,并返回删除的元素
36 print(return_result) #g 返回删除的元素
37 #删除指定位置
38 list.pop(1) #list.pop(1) = del list[1]
39 print(list) #['a', 'd', 'e', 'f']
40
41 #列表查找 查找列表元素
42 #查找列表中某一元素所在的位置
43 list = ['a', 'b', 'c', 'b', 'e', 'b']
44 print(list.index('b')) #1 只能找到第一个
45 print(list[list.index('b')]) #b
46 #统计列表中同一个元素的数量
47 print(list.count('b')) #3
48 #清除列表中的元素
49 list.clear() #没有返回值
50 print(list) #[]
51 list = ['a', 'b', 'c', 'd', 'e', 'f']
52 #列表反转
53 list.reverse() #没有返回值
54 print(list) #['f', 'e', 'd', 'c', 'b', 'a']
55 #列表排序
56 list.sort() #默认升序排序 也可以降序排序 sort(reverse=True)
57 print(list) #['a', 'b', 'c', 'd', 'e', 'f']
58 #排序规则,由大到小依次为:特殊符号 数字 大写字母 小写字母
59 #合并列表
60 list_01 = [1, 2, 3, 4]
61 list_02 = ['a', 'b', 'c', 'd']
62 list_01.extend(list_02)
63 print(list_01) #[1, 2, 3, 4, 'a', 'b', 'c', 'd']
64 #删除整个列表
65 del list_02
66 #print(list_02) #NameError: name 'list_02' is not defined
67
68 #列表复制
69 #浅复制 浅copy 仅复制一层
70 #方法1
71 list = ['a', 'b', ['c','d'], 'e']
72 list_copy = list[:]
73 print(list_copy) #['a', 'b', ['c', 'd'], 'e']
74 list[2][0] = 11
75 print(list_copy) #['a', 'b', [11, 'd'], 'e'] 修改list,list_copy中[11, 'd']也会改变,因为浅复制仅复制了[11, 'd']的地址
76
77 #方法2
78 list = ['a', 'b', ['c','d'], 'e']
79 list_copy02 = list.copy()
80 print(list_copy02) #['a', 'b', ['c', 'd'], 'e']
81 list[2][0] = 11
82 print(list_copy02) #['a', 'b', [11, 'd'], 'e'] 修改list,list_copy中[11, 'd']也会改变,因为浅复制仅复制了[11, 'd']的地址
83
84 #方法3
85 import copy
86 list = ['a', 'b', ['c','d'], 'e']
87 list_copy03 = copy.copy(list)
88 print(list_copy03) #['a', 'b', ['c', 'd'], 'e']
89 list[2][0] = 11
90 print(list_copy03) #['a', 'b', [11, 'd'], 'e']
91 #print(list_copy02)
92 #深复制 深copy
93 import copy
94 list = ['a', 'b', ['c','d'], 'e']
95 list_copy04 = copy.deepcopy(list)
96 print(list_copy04) #['a', 'b', ['c', 'd'], 'e']
97 list[2][0] = 11
98 print(list) #['a', 'b', [11, 'd'], 'e']
99 print(list_copy04) #['a', 'b', ['c', 'd'], 'e']
100 #lsit改变了,但是list_copy04却没有改变,deepcopy()方法是将list中的所有元素完全克隆了一份给list_copy04