文章目錄
- 1 列表(List)
- 1.1 列表常用方法
- 1.2 列表的特殊用途
- 1.2.1 實現堆棧(后進先出)
- 1.2.2 實現隊列(先進先出)
- 1.3 列表推導式
- 1.4 嵌套列表推導式
- 2 del 語句
- 3 元組(Tuple)
- 4 集合(Set)
- 4.1 集合操作
- 4.2 集合推導式
- 5 字典(Dictionary)
- 5.1 字典基本操作
- 5.2 字典創建方式
- 5.3 字典遍歷
- 6 循環技巧
- 6.1 遍歷字典
- 6.2 帶索引遍歷序列
- 6.3 同時遍歷多個序列
- 6.4 反向遍歷
- 6.5 排序遍歷
- 7 序列比較
1 列表(List)
列表是 Python 中最常用的數據結構之一,是有序、可變的元素集合,支持多種操作方法。
1.1 列表常用方法
方法 | 功能描述 |
---|---|
list.append(x) | 在列表末尾添加元素 x |
list.extend(iterable) | 擴展列表,添加可迭代對象的所有元素 |
list.insert(i, x) | 在索引 i 處插入元素 x |
list.remove(x) | 刪除第一個值為 x 的元素 |
list.pop([i]) | 移除并返回索引 i 處的元素(默認最后一個) |
list.clear() | 清空列表 |
list.index(x[, start[, end]]) | 返回 x 第一次出現的索引 |
list.count(x) | 統計 x 在列表中出現的次數 |
list.sort(key=None, reverse=False) | 就地排序列表 |
list.reverse() | 反轉列表元素 |
list.copy() | 返回列表的淺拷貝 |
示例:
fruits = ['orange', 'apple', 'pear', 'banana']
print(fruits.count('apple')) # 1
print(fruits.index('banana')) # 3fruits.append('grape')
fruits.sort()
print(fruits) # ['apple', 'banana', 'grape', 'orange', 'pear']fruits.reverse()
print(fruits) # ['pear', 'orange', 'grape', 'banana', 'apple']
1.2 列表的特殊用途
1.2.1 實現堆棧(后進先出)
stack = [3, 4, 5]
stack.append(6) # 入棧
stack.append(7)
print(stack) # [3, 4, 5, 6, 7]print(stack.pop()) # 7(出棧)
print(stack) # [3, 4, 5, 6]
1.2.2 實現隊列(先進先出)
列表作為隊列效率較低,推薦使用collections.deque
:
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # 入隊
queue.append("Graham")print(queue.popleft()) # 'Eric'(出隊)
print(queue) # deque(['John', 'Michael', 'Terry', 'Graham'])
1.3 列表推導式
簡潔創建列表的方式,格式:[表達式 for 變量 in 可迭代對象 if 條件]
示例:
# 創建平方列表
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# 過濾偶數
even_numbers = [x for x in range(20) if x % 2 == 0]
print(even_numbers) # [0, 2, 4, ..., 18]# 處理字符串列表
words = [' apple', 'banana ', ' cherry ']
stripped = [word.strip() for word in words]
print(stripped) # ['apple', 'banana', 'cherry']
1.4 嵌套列表推導式
用于處理復雜結構,如矩陣轉置:
# 3x4矩陣
matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],
]# 轉置矩陣(行變列)
transposed = [[row[i] for row in matrix] for i in range(4)]
print(transposed) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
2 del 語句
用于刪除列表元素、切片或變量:
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0] # 刪除索引0的元素
print(a) # [1, 66.25, 333, 333, 1234.5]del a[2:4] # 刪除切片
print(a) # [1, 66.25, 1234.5]del a[:] # 清空列表
print(a) # []del a # 刪除變量a
3 元組(Tuple)
元組是有序、不可變的元素集合,用逗號分隔,通常用圓括號包裹。
- 不可變:創建后不能修改元素
- 可包含任意類型元素,包括可變對象
- 支持索引和切片操作
- 可用于打包和解包
示例:
t = 12345, 54321, 'hello!' # 元組打包
print(t[0]) # 12345# 元組嵌套
u = t, (1, 2, 3, 4, 5)
print(u) # ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))# 元組解包
x, y, z = t
print(x, y, z) # 12345 54321 hello!# 單元素元組(注意逗號)
singleton = 'hello',
print(singleton) # ('hello',)
4 集合(Set)
集合是無序、不重復的元素集合,支持數學集合運算。
4.1 集合操作
basket = {'apple', 'orange', 'apple', 'pear'}
print(basket) # {'orange', 'pear', 'apple'}(自動去重)# 成員檢測
print('orange' in basket) # True# 集合運算
a = set('abracadabra')
b = set('alacazam')
print(a - b) # 差集:{'r', 'd', 'b'}
print(a | b) # 并集:{'a','c','r','d','b','m','z','l'}
print(a & b) # 交集:{'a', 'c'}
print(a ^ b) # 對稱差集:{'r','d','b','m','z','l'}
4.2 集合推導式
# 創建不包含某些元素的集合
a = {x for x in 'abracadabra' if x not in 'abc'}
print(a) # {'r', 'd'}
5 字典(Dictionary)
字典是鍵值對的無序集合,鍵必須唯一且不可變,值可以是任意類型。
5.1 字典基本操作
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127 # 添加鍵值對
print(tel) # {'jack': 4098, 'sape': 4139, 'guido': 4127}print(tel['jack']) # 4098(訪問值)del tel['sape'] # 刪除鍵值對
print(list(tel)) # ['jack', 'guido'](獲取鍵列表)
5.2 字典創建方式
# 1. 直接創建
d1 = {'name': 'Alice', 'age': 30}# 2. 使用dict()構造函數
d2 = dict([('name', 'Bob'), ('age', 25)])# 3. 字典推導式
d3 = {x: x*2 for x in range(3)} # {0:0, 1:2, 2:4}# 4. 關鍵字參數
d4 = dict(name='Charlie', age=35)
5.3 字典遍歷
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items(): # 同時獲取鍵和值print(k, v)
6 循環技巧
6.1 遍歷字典
for k, v in knights.items():print(k, v)
6.2 帶索引遍歷序列
for i, v in enumerate(['tic', 'tac', 'toe']):print(i, v) # 0 tic, 1 tac, 2 toe
6.3 同時遍歷多個序列
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):print(f"What is your {q}? It is {a}.")
6.4 反向遍歷
for i in reversed(range(1, 10, 2)):print(i) # 9,7,5,3,1
6.5 排序遍歷
basket = ['apple', 'orange', 'apple', 'pear']
for f in sorted(set(basket)): # 去重并排序print(f) # apple, banana, orange, pear
7 序列比較
序列比較使用字典式順序:
- 比較對應位置元素,直到找到不同元素
- 短序列是長序列的前綴則短序列更小
- 支持同類型序列比較
(1, 2, 3) < (1, 2, 4) # True
[1, 2, 3] < [1, 2, 4] # True
'ABC' < 'C' < 'Pascal' < 'Python' # True
(1, 2, 3) == (1.0, 2.0, 3.0) # True