Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
filter():過濾可迭代物件
語法:
filter(function, iterable)filter() 會用一個函數來「篩選」可迭代物件中的元素,只保留函數回傳 True 的那些。nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 篩選偶數
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4, 6, 8, 10]
# 篩選大於 5 的數
big = list(filter(lambda x: x > 5, nums))
print(big) # [6, 7, 8, 9, 10]用具名函數來過濾
除了 lambda,也可以傳入一般的具名函數。當過濾邏輯比較複雜時,具名函數更清楚。
def is_positive(n):
return n > 0
nums = [-3, -1, 0, 2, 5, -4, 8]
result = list(filter(is_positive, nums))
print(result) # [2, 5, 8]function 傳 None
如果 function 傳入 None,filter() 會自動過濾掉「假值」(False、0、空字串、None 等)。
data = [0, 1, '', 'hello', None, True, False, [], [1, 2]]
# 過濾掉假值
truthy = list(filter(None, data))
print(truthy) # [1, 'hello', True, [1, 2]]filter() vs 列表推導式
filter() 和列表推導式都能做篩選,通常列表推導式更 Pythonic,但 filter() 在搭配已有函數時更簡潔。
nums = [1, 2, 3, 4, 5, 6]
# filter 寫法
evens_filter = list(filter(lambda x: x % 2 == 0, nums))
# 列表推導式寫法
evens_comp = [x for x in nums if x % 2 == 0]
print(evens_filter) # [2, 4, 6]
print(evens_comp) # [2, 4, 6]
# 搭配已有函數時 filter 更簡潔
words = ['hello', '', 'world', '', 'python']
non_empty = list(filter(None, words))
print(non_empty) # ['hello', 'world', 'python']filter 回傳迭代器
filter() 回傳的是一個迭代器(filter object),不是列表。需要時可以用 list() 轉換,或直接在 for 迴圈中使用。
nums = [1, 2, 3, 4, 5]
result = filter(lambda x: x > 3, nums)
print(type(result)) # <class 'filter'>
# 直接在 for 迴圈中使用
for n in filter(lambda x: x > 3, nums):
print(n) # 4, 5小小綜合例子
# 電商商品篩選系統
products = [
{'name': '筆電', 'price': 35000, 'in_stock': True},
{'name': '滑鼠', 'price': 500, 'in_stock': True},
{'name': '鍵盤', 'price': 2000, 'in_stock': False},
{'name': '螢幕', 'price': 12000, 'in_stock': True},
{'name': '耳機', 'price': 3000, 'in_stock': True},
{'name': '手機殼', 'price': 300, 'in_stock': False},
]
# 篩選有庫存的商品
in_stock = list(filter(lambda p: p['in_stock'], products))
# 篩選價格在 1000~10000 之間的商品
def price_range(p):
return 1000 <= p['price'] <= 10000
affordable = list(filter(price_range, in_stock))
print('=== 有庫存且價格 1000~10000 的商品 ===')
for p in affordable:
print(f" {p['name']}: ${p['price']}")
# 統計
print(f'\n共 {len(affordable)} 件商品符合條件')
total = sum(p['price'] for p in affordable)
print(f'總價:${total}')
# === 有庫存且價格 1000~10000 的商品 ===
# 螢幕: $12000 (不符合,超過10000)
# 耳機: $3000
# 共 1 件商品符合條件
# 總價:$3000