第4章:介紹python物件型別/4.1 python的核心資料型別/4.3 列表
-
獲取操作
-
>>> 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}
>>>