列表示一种处理有序项目的数据结构,列表与元祖的区别就是数据可变

  • 创建列表
1
2
3
4
5
6
#创建空列表
list1 = []
list2 = list()

#创建有内容列表,列表可包含列表,元祖
list3 = ['a',3,(1,),[1,2,3,'pyhton']]
  • 列表操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#range函数构建数字列表,列表相加
In [14]: a
Out[14]: [1, 2, 3, 4, 5]

In [15]: b = range(10,1,-1)

In [16]: b
Out[16]: [10, 9, 8, 7, 6, 5, 4, 3, 2]

In [17]: a + b
Out[17]: [1, 2, 3, 4, 5, 10, 9, 8, 7, 6, 5, 4, 3, 2]

In [18]: c = a+b

In [19]: c
Out[19]: [1, 2, 3, 4, 5, 10, 9, 8, 7, 6, 5, 4, 3, 2]

#列表相乘
In [20]: a * 3
Out[20]: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

#追加元素
In [23]: b
Out[23]: [10, 9, 8, 7, 6, 5, 4, 3, 2]

In [24]: b.append([5,3,1])

In [25]: b
Out[25]: [10, 9, 8, 7, 6, 5, 4, 3, 2, [5, 3, 1]]

#删除列表
In [21]: del a

In [22]: a
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-22-60b725f10c9c> in <module>()
----> 1 a

NameError: name 'a' is not defined

#删除列表元素
In [29]: b
Out[29]: [10, 9, 8, 7, 6, 5, 4, 3, 2, [5, 3, 1]]

In [30]: b.remove(10)

In [31]: b
Out[31]: [9, 8, 7, 6, 5, 4, 3, 2, [5, 3, 1]]

#查看列表中是否含有某一元素,存在返回True,不存在返回False
In [34]: a = range(1,6)

In [35]: a
Out[35]: [1, 2, 3, 4, 5]

In [36]: 3 in a
Out[36]: True

In [37]: 3 not in a
Out[37]: False

#添对象
In [1]: a = range(1,6)

In [2]: a
Out[2]: [1, 2, 3, 4, 5]

In [3]: a.append(range(7,10))

In [4]: a
Out[4]: [1, 2, 3, 4, 5, [7, 8, 9]]

#在特定位置前面添加对象
In [6]: b
Out[6]: [1, 2, 3, 4, 5]

In [7]: b.insert(3,range(7,9))

In [8]: b
Out[8]: [1, 2, 3, [7, 8], 4, 5]

#将数据融合到列表中In [12]: a
Out[12]: [1, 2, 3, 4, 5]

In [13]: a.extend(range(7,9))

In [14]: a
Out[14]: [1, 2, 3, 4, 5, 7, 8],注意与append的区别

#列表排序
In [19]: a
Out[19]: [9, 8, 7, 6, 5, 4, 3, 2]

In [20]: a.sort()

In [21]: a
Out[21]: [2, 3, 4, 5, 6, 7, 8, 9]

#反向
In [23]: a
Out[23]: [2, 3, 4, 5, 6, 7, 8, 9]

In [24]: a.reverse()

In [25]: a
Out[25]: [9, 8, 7, 6, 5, 4, 3, 2]

#按照索引删除元素
In [25]: a
Out[25]: [9, 8, 7, 6, 5, 4, 3, 2]

In [26]: a.pop(0)
Out[26]: 9

In [27]: a
Out[27]: [8, 7, 6, 5, 4, 3, 2]

#没有索引默认删除最后一个元素
In [28]: a
Out[28]: [8, 7, 6, 5, 4, 3, 2]

In [29]: a.pop()
Out[29]: 2

In [30]: a
Out[30]: [8, 7, 6, 5, 4, 3]

#迭代追加元素 注意与appen和insert的区别
In [35]: a
Out[35]: [1, 2, 3]

In [36]: a.extend('abc')

In [37]: a
Out[37]: [1, 2, 3, 'a', 'b', 'c']