-
获取操作
-
>>> L = [123,'abc',1.23]
>>> L[0] 从左边开始获取
123
>>> L[-1] 从右边开始获取
1.23
>>>
-
追加元素
-
>>> L
[123, 'abc', 1.23]
>>> L.append('xyz')
>>> L
[123, 'abc', 1.23, 'xyz']
-
追加一个列表
-
>>> L + ["A","B","C"]
[123, 'abc', 1.23, 'xyz', 'A', 'B', 'C']
-
弹出一个元素
-
>>> L
[123, 'abc', 1.23, 'xyz']
>>> L.pop(3)
'xyz'
>>> L
[123, 'abc', 1.23]
>>>
-
列表排序
-
>>> L
[123, 'abc', 1.23]
>>> L.sort() #要求列表中数据类型一致才行,要么都是字符串,要么都是数字,不能数字和列表混合
Traceback (most recent call last):
File "<pyshell#114>", line 1, in <module>
L.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
>>> M=['a','c','f','a']
>>> M.sort()
>>> M
['a', 'a', 'c', 'f']
-
列表反转
-
>>> L
[123, 'abc', 1.23]
>>> L.reverse()
>>> L
[1.23, 'abc', 123]
>>>
-
边界检查
-
>>> L
[1.23, 'abc', 123]
>>> L[99] #超出边界了
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
L[99]
IndexError: list index out of range
>>>
-
嵌套列表
-
>>> L = [[1,2,3],["abc","dcd"]]
>>> L[0][2]
3
>>> L[1][1]
'dcd'
-
列表解析:获取每一行第二个数据
-
>>> M = [[1,2,3],[4,5,6],[7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> col2 = [row[1] for row in M]
>>> col2
[2, 5, 8]
>>>
-
列表解析:获取每一行第二个数据并运算
-
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> col2 = [row[1]+1 for row in M]
>>> col2
[3, 6, 9]
>>>
-
列表解析:获取每一行第二个数据并附加过滤条件
-
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> col2 = [row[1] for row in M if row[1] %2 == 0]
>>> col2
[2, 8]
>>>
-
列表解析:取对角线的值
- 对角线的值对应下标:[0][0]、[1][1]、[2][2]
-
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> col2 = [M[i][i] for i in [0,1,2]]
>>> col2
[1, 5, 9]
>>>
-
列表解析:对每一行求和
-
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> col2 = [sum(row) for row in M]
>>> col2
[6, 15, 24]
-
列表解析:以向量形式返回每一行和
-
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> col2 = (sum(row) for row in M)
>>> next(col2)
6
>>> next(col2)
15
>>> next(col2)
24
-
列表解析:以集合形式返回每一行和
-
>>> M
[[1, 2, 3], [4, 5, 6], [10, 0, 5]]
>>> col2 = {sum(row) for row in M}
>>> col2
{6, 15} #集合不能用重复值,所以15就只有1个
>>>
-
列表解析:以字典形式返回每一行和
-
>>> M
[[1, 2, 3], [4, 5, 6], [10, 0, 5]]
>>> col2 = {i:sum(M[i]) for i in range(len(M))}
>>> col2
{0: 6, 1: 15, 2: 15}
>>>