一、 列表詳解
1 列表方法總結
方法 | 描述 | 等價操作 | rust Vec類似操作 |
---|---|---|---|
list.append(x) | 末尾添加元素 | a[len(a):] = [x] | vec.push(x); |
list.extend(iterable) | 擴展列表 | a[len(a):] = iterable | vec.extend([4, 5, 6]); 或者更高效:vec.extend_from_slice(&[4, 5, 6]); |
list.insert(i, x ) | 指定位置插入 | vec.insert(1,X); | |
list.remove(x) | 刪除第一個值為x的元素 | ||
list.pop([i]) | 移除并返回指定位置元素 | vec.pop(); 及vec.remove(1); | |
list.clear() | 清空列表 | del a[:] | vec.clear() |
list.index(x[, start[, end]]) | 返回第一個x的索引 | ||
list.count(x) | 統計x出現次數 | ||
list.sort(*, key=None, reverse=False) | 原地排序 | vec.sort();vec.sort_by( | |
list.reverse() | 原地反轉 | ||
list.copy() | 淺拷貝 | a[:] | |
示例代碼 |
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']fruits.count('apple') # 2
fruits.index('banana') # 3
fruits.index('banana', 4) # 6 (從索引4開始找)fruits.reverse() # 反轉列表
fruits.append('grape') # 添加元素
fruits.sort() # 排序
fruits.pop() # 移除并返回最后一個元素
2 用列表實現堆棧(LIFO)
stack = [3, 4, 5]
stack.append(6) # 壓棧 → [3, 4, 5, 6]
stack.append(7) # 壓棧 → [3, 4, 5, 6, 7]
stack.pop() # 出棧 → 7, 棧變為 [3, 4, 5, 6]
stack.pop() # 出棧 → 6, 棧變為 [3, 4, 5]
3 用列表實現隊列(FIFO)- 不推薦
# 效率低,推薦使用 collections.deque
from collections import dequequeue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # 入隊
queue.append("Graham") # 入隊
queue.popleft() # 出隊 → 'Eric'
queue.popleft() # 出隊 → 'John'
4 列表推導式
基本語法
# 傳統方式
squares = []
for x in range(10):squares.append(x**2)# 列表推導式(推薦)
squares = [x**2 for x in range(10)]
復雜示例
# 條件過濾
vec = [-4, -2, 0, 2, 4]
[x for x in vec if x >= 0] # [0, 2, 4]# 應用函數
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
[weapon.strip() for weapon in freshfruit] # 去除空格# 嵌套循環
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]# 展平嵌套列表
vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem] # [1,2,3,4,5,6,7,8,9]
5 嵌套的列表推導式
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)]
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]# 更簡潔的方式(推薦)
list(zip(*matrix))
二、 del 語句
a = [-1, 1, 66.25, 333, 333, 1234.5]del a[0] # 刪除索引0的元素 → [1, 66.25, 333, 333, 1234.5]
del a[2:4] # 刪除切片 → [1, 66.25, 1234.5]
del a[:] # 清空列表 → []
del a # 刪除整個變量
三、元組和序列
元組基本操作
# 創建元組
t = 12345, 54321, 'hello!' # 打包
t[0] # 12345# 解包
x, y, z = t# 嵌套元組
u = t, (1, 2, 3, 4, 5)# 不可變性(會報錯)
# t[0] = 88888# 包含可變對象的元組
v = ([1, 2, 3], [3, 2, 1])
v[0][0] = 999 # 可以修改列表內容
特殊元組
empty = () # 空元組
singleton = 'hello', # 單元素元組(注意逗號)
len(empty) # 0
len(singleton) # 1
四、集合
集合操作
# 創建集合
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
# {'orange', 'banana', 'pear', 'apple'} (去重)# 成員檢測
'orange' in basket # True# 集合運算
a = set('abracadabra') # {'a', 'r', 'b', 'c', 'd'}
b = set('alacazam') # {'a', 'c', 'l', 'm', 'z'}a - b # 差集 {'r', 'd', 'b'}
a | b # 并集 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
a & b # 交集 {'a', 'c'}
a ^ b # 對稱差集 {'r', 'd', 'b', 'm', 'z', 'l'}# 集合推導式
{x for x in 'abracadabra' if x not in 'abc'} # {'r', 'd'}
五、字典
字典操作
# 創建字典
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127 # 添加/修改# 訪問和刪除
tel['jack'] # 4098
del tel['sape'] # 刪除鍵
'guido' in tel # True# 構造函數
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
dict(sape=4139, guido=4127, jack=4098) # 關鍵字參數方式# 字典推導式
{x: x**2 for x in (2, 4, 6)} # {2: 4, 4: 16, 6: 36}
六、循環的技巧
字典循環
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():print(k, v)
枚舉循環
for i, v in enumerate(['tic', 'tac', 'toe']):print(i, v) # 0 tic, 1 tac, 2 toe
并行循環
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}.')
反向和排序循環
# 反向循環
for i in reversed(range(1, 10, 2)):print(i) # 9,7,5,3,1# 排序循環
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for i in sorted(basket): # 按順序循環print(i)# 去重排序循環
for f in sorted(set(basket)):print(f) # apple, banana, orange, pear
七、深入條件控制
比較運算符
# 鏈式比較
a < b == c # 等價于 a < b and b == c# 布爾運算
A and not B or C # 等價于 (A and (not B)) or C# 短路特性
string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
non_null = string1 or string2 or string3 # 'Trondheim'
八、序列比較
字典式順序比較
(1, 2, 3) < (1, 2, 4) # True
[1, 2, 3] < [1, 2, 4] # True
'ABC' < 'C' < 'Pascal' < 'Python' # True
(1, 2, 3, 4) < (1, 2, 4) # True (前兩個元素相等,第一個序列更長)
(1, 2) < (1, 2, -1) # True (第二個序列更長)
(1, 2, 3) == (1.0, 2.0, 3.0) # True (數值相等)
九、重要注意事項
-
列表方法:insert, remove, sort 等方法返回 None,不要期待它們返回值
-
可變性:列表可變,元組不可變
-
集合去重:集合自動去除重復元素
-
字典鍵:必須是不可變類型(字符串、數字、元組等)
-
循環技巧:善用 enumerate(), zip(), reversed(), sorted(), set()
這些數據結構是Python編程的基礎,熟練掌握它們能大大提高編碼效率。