2025年9月11日 星期四

Python 進階語法範例

  Python 進階語法範例

 

1️⃣ 列表推導式 (List Comprehension)

prices = [100, 105, 102, 110] returns = [(prices[i+1] - prices[i]) / prices[i] * 100 for i in range(len(prices)-1)] print(returns) # [5.0, -2.86, 7.84]

解釋:

  • prices 是每日收盤價清單。

  • range(len(prices)-1) 產生 index [0,1,2],用來抓前一天和下一天的價格差。

  • (prices[i+1] - prices[i]) / prices[i] * 100 計算每日報酬率(百分比)。

  • [...] for i in range(...) → 列表推導式,把每個計算結果生成新的清單 returns。


2️⃣ 字典推導式 (Dict Comprehension)

fields = ["open", "high", "low", "close"] index_map = {field: i for i, field in enumerate(fields)} print(index_map) # {'open': 0, 'high': 1, 'low': 2, 'close': 3}

解釋:

  • enumerate(fields) → 同時拿到索引 i 和對應元素 field。

  • {field: i for ...} → 字典推導式,把元素作為 key,索引作為 value。

  • index_map 會把欄位名稱對應到位置,方便後續抓資料。


3️⃣ Lambda + Reduce

from functools import reduce daily_returns = [0.01, -0.02, 0.03, 0.01] cumulative = reduce(lambda x, y: x * (1 + y), daily_returns, 1) - 1 print(round(cumulative, 4)) # 0.0297

解釋:

  • reduce(func, iterable, start) → 把 iterable 依序套用 func,從 start 開始。

  • lambda x, y: x * (1 + y) → 匿名函數,把累積報酬與每日報酬結合。

  • 1 → 初始值 (本金)。

  • -1 → 最後減去本金,得到純報酬率。


4️⃣ Enumerate

prices = [100, 102, 101, 104] for i, price in enumerate(prices): print(f"Day {i}: Price={price}")

解釋:

  • enumerate(prices) → 同時拿到 index 和價格。

  • f"Day {i}: Price={price}" → f-string 格式化,顯示哪一天價格。


5️⃣ Zip

dates = ["2025-09-08", "2025-09-09", "2025-09-10"] prices = [100, 102, 101] for d, p in zip(dates, prices): print(f"{d}: {p}")

解釋:

  • zip(dates, prices) → 將兩個序列配對,迭代時同時取得日期和價格。

  • 適合把多個清單「同步」處理。


6️⃣ 裝飾器 (Decorator)

import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f"執行時間: {time.time() - start:.4f} 秒") return result return wrapper @timer def simulate_trade(): return sum([i**2 for i in range(10**6)]) simulate_trade()

解釋:

  • @timer → 把 simulate_trade 包裝在 timer 裡。

  • wrapper(*args, **kwargs) → 可接受任何參數的中介函數。

  • time.time() → 計算程式執行時間。

  • sum([i**2 for i in range(10**6)]) → 模擬計算大量交易策略。

  • 執行時會印出耗時,方便優化程式效率。


7️⃣ 生成器 (Generator, yield)

def price_stream(prices): for p in prices: yield p prices = [100, 102, 104, 103] for p in price_stream(prices): print("Next price:", p)

解釋:

  • yield → 生成器,每次迭代只產生一個值,不會把全部資料載入記憶體。

  • 適合大數據或串流資料。

  • for p in price_stream(prices) → 每次取一個價格,用完再取下一個。


8️⃣ 型別註解 (Type Hint)

def moving_average(prices: list[float], window: int) -> list[float]: return [sum(prices[i:i+window]) / window for i in range(len(prices)-window+1)] print(moving_average([100, 101, 102, 103, 104], 3)) # [101.0, 102.0, 103.0]

解釋:

  • prices: list[float] → 說明 prices 是浮點數清單。

  • window: int → 視窗大小是整數。

  • -> list[float] → 回傳結果是浮點數清單。

  • [sum(prices[i:i+window]) / window ...] → 計算移動平均。

 

沒有留言:

張貼留言