【Python 基礎語法 #5】python 小技巧 - list comprehension 使用範例

介紹 Python list comprehension — 一行產生 list、迴圈 + if 過濾、節省程式碼行數但要注意可讀性。

前言

小技巧篇通常不會介紹太詳細的觀念,
通常都只是看到網路上的一些不錯的用法,
就做一點筆記當作小抄這樣。

不會小技巧依然可以寫出 python !!!,
但請不要「本末倒置」為了使用小技巧導致自己的程式失去了可讀性!!!

list comprehension

list comprehension 是一個能夠以一行處理掉 list 邏輯的 python 程式碼,
通常使用時,可以更節省空間,並且縮短程式碼的行數
(相反的,也可能減少了程式碼易讀性)

基礎 list comprehension 使用方法

最基本的使用方法,透過 list comprehension 快速產生一個連續數值的 list

ans = [x  for x in range(10)]
print(ans)
  • 結果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list comprehension 搭配 if 用法

稍微進階一點的使用方法,透過 list comprehension 搭配 if,
會呈現有點像是「過濾」的效果。

x_list = [-1, -2, 3]
ans = [x  for x in x_list if x < 0]
print(ans)
  • 結果:
[-1, -2]

list comprehension 搭配 if-else 三元運算子

再更進階一點的使用方法,透過 list comprehension 搭配 if-else 三元運算子,
可以「對每個值進行處理」,所以可以達成向下面製作出「絕對值」的效果。

x_list = [-1, -2, 3]
ans = [x if x>0 else -x for x in x_list]
print(ans)
  • 結果:
[1, 2, 3]

Reference

使用 Hugo 建立
主題 StackJimmy 設計