寫了三行能寫一行的代碼,是技術問題
看到別人的 Python 代碼,短短一行完成了你寫五行才能做的事,不是炫技,是真的更簡潔、更 Pythonic。
這篇文章整理列表推導式和最常用的內置函數,每個都配可以直接拿走的代碼片段。
列表推導式
列表推導式(List Comprehension)是 Python 最具代表性的語法之一,用一行代替 for 循環構建列表。
基本語法:
[表達式 for 元素 in 可迭代對象 if 條件]
基礎:替代 for 循環
# 傳統寫法
squares = []
for x in range(10):
squares.append(x ** 2)
# 列表推導式
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
加上條件過濾
# 只取偶數的平方
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
# 過濾列表中的空字符串
words = ["hello", "", "world", "", "python"]
clean = [w for w in words if w]
# ["hello", "world", "python"]
字符串處理
names = ["alice", "bob", "charlie"]
# 首字母大寫
capitalized = [name.capitalize() for name in names]
# ["Alice", "Bob", "Charlie"]
# 過濾長度大於3的名字並轉大寫
result = [name.upper() for name in names if len(name) > 3]
# ["ALICE", "CHARLIE"]
嵌套列表推導式(二維數組展平)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 展平二維列表
flat = [x for row in matrix for x in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
字典推導式和集合推導式
# 字典推導式
words = ["apple", "banana", "cherry"]
word_lengths = {word: len(word) for word in words}
# {"apple": 5, "banana": 6, "cherry": 6}
# 集合推導式(自動去重)
nums = [1, 2, 2, 3, 3, 3]
unique = {x ** 2 for x in nums}
# {1, 4, 9}
生成器表達式:省內存的版本
列表推導式會一次性把所有元素放進內存,數據量大時改用生成器表達式(把 [] 換成 ()):
# 列表推導式:立即生成所有元素
total = sum([x ** 2 for x in range(1000000)])
# 生成器表達式:逐個生成,省內存
total = sum(x ** 2 for x in range(1000000)) # 直接省掉外層[]
最常用的內置函數
Python 內置了大量高質量函數,學會用這些,很多需要自己手寫的邏輯可以省掉。
map():對每個元素應用函數
nums = [1, 2, 3, 4, 5]
# 每個數平方
squares = list(map(lambda x: x ** 2, nums))
# [1, 4, 9, 16, 25]
# 字符串列表轉整數
str_nums = ["1", "2", "3"]
int_nums = list(map(int, str_nums))
# [1, 2, 3]
很多情況下列表推導式比
map更可讀,但map在配合現成函數時更簡潔。
filter():過濾元素
nums = [1, -2, 3, -4, 5, -6]
# 只保留正數
positives = list(filter(lambda x: x > 0, nums))
# [1, 3, 5]
# filter(None, ...) 過濾所有假值(0、None、空字符串等)
mixed = [0, 1, "", "hello", None, 42]
truthy = list(filter(None, mixed))
# [1, "hello", 42]
zip():並行遍歷多個列表
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
# 配對
pairs = list(zip(names, scores))
# [("Alice", 95), ("Bob", 87), ("Charlie", 92)]
# 配合 for 循環
for name, score in zip(names, scores):
print(f"{name}: {score}")
# 解壓(zip 的逆操作)
unzipped_names, unzipped_scores = zip(*pairs)
enumerate():遍歷時帶索引
fruits = ["apple", "banana", "cherry"]
# 不用 range(len(...))
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
# 從1開始編號
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
sorted() 和 sort():排序
nums = [3, 1, 4, 1, 5, 9, 2, 6]
# sorted() 返回新列表,不改變原列表
asc = sorted(nums) # [1, 1, 2, 3, 4, 5, 6, 9]
desc = sorted(nums, reverse=True) # [9, 6, 5, 4, 3, 2, 1, 1]
# sort() 原地排序,返回 None
nums.sort()
# 按自定義規則排序
words = ["banana", "apple", "cherry", "date"]
by_length = sorted(words, key=len) # 按長度
by_second = sorted(words, key=lambda w: w[1]) # 按第二個字母
# 按字典的某個字段排序
users = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
by_age = sorted(users, key=lambda u: u["age"])
any() 和 all():批量邏輯判斷
nums = [1, 2, 3, 4, 5]
# any():至少一個爲真
has_even = any(x % 2 == 0 for x in nums) # True
has_neg = any(x < 0 for x in nums) # False
# all():全部爲真
all_positive = all(x > 0 for x in nums) # True
all_even = all(x % 2 == 0 for x in nums) # False
# 實際用途:驗證表單字段是否全部填寫
fields = {"name": "Alice", "email": "alice@example.com", "age": 28}
is_complete = all(fields.values()) # True(所有值都是真值)
min() 和 max():最值
nums = [3, 1, 4, 1, 5, 9]
print(min(nums)) # 1
print(max(nums)) # 9
# 帶 key 參數
words = ["banana", "apple", "cherry"]
shortest = min(words, key=len) # "apple"
longest = max(words, key=len) # "banana" 或 "cherry"
# 找字典列表中某字段的最值
users = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
youngest = min(users, key=lambda u: u["age"])
# {"name": "Alice", "age": 25}
sum():求和
nums = [1, 2, 3, 4, 5]
print(sum(nums)) # 15
print(sum(nums, 100)) # 115(從100開始累加)
# 計算嵌套列表的總和
matrix = [[1, 2], [3, 4], [5, 6]]
total = sum(sum(row) for row in matrix) # 21
isinstance():類型判斷
x = 42
# 判斷單個類型
print(isinstance(x, int)) # True
print(isinstance(x, str)) # False
# 同時判斷多個類型
print(isinstance(x, (int, float))) # True(是數字就行)
# 實際用途:函數參數校驗
def process(data):
if not isinstance(data, (list, tuple)):
raise TypeError(f"期望列表或元組,得到 {type(data).__name__}")
return [x * 2 for x in data]
round()、abs()、divmod()
# round():四捨五入
round(3.14159, 2) # 3.14
round(3.5) # 4(Python 3 是銀行家舍入,偶數優先)
round(2.5) # 2
# abs():絕對值
abs(-5) # 5
abs(-3.14) # 3.14
# divmod():同時得到商和餘數
q, r = divmod(17, 5) # q=3, r=2
一行代碼速查
收藏這幾個常用的單行技巧:
# 列表去重(保留順序)
seen = set()
unique = [x for x in lst if not (x in seen or seen.add(x))]
# 或者不需要保序時
unique = list(set(lst))
# 列表展平(一層)
flat = [x for sublist in nested for x in sublist]
# 統計元素出現次數
from collections import Counter
counts = Counter(["a", "b", "a", "c", "b", "a"])
# Counter({"a": 3, "b": 2, "c": 1})
# 字典合併(Python 3.9+)
merged = dict1 | dict2
# 交換兩個變量
a, b = b, a
# 檢查列表是否爲空
if not my_list:
print("列表爲空")
想把這些片段直接跑起來驗證效果,粘到 Python 在線運行工具 裏,Python 3.12 環境,改完即看結果,不用裝任何東西。



加載中...