iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
Software Development

學會 Python 不可怕:我每天學一點的 30 天筆記系列 第 22

Day22 : 列表推導式 & 簡化技巧 – 一行寫出迴圈

  • 分享至 

  • xImage
  •  

1. 什麼是「列表推導式」?
在 Python 裡,常常需要「用迴圈」產生一個新列表:
https://ithelp.ithome.com.tw/upload/images/20251006/201788727oBcUKeXB5.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251006/20178872mSICTzcSic.png
但其實可以用一行寫完:
https://ithelp.ithome.com.tw/upload/images/20251006/20178872huWfNxSdzx.png
輸出的結果是一樣的
https://ithelp.ithome.com.tw/upload/images/20251006/20178872AKUIR9zHUz.png
這種寫法就叫做 「列表推導式」,它的基本語法是:[運算式 for 變數 in 可迭代物件]
運算式 : 要放入列表的內容(可以是運算、函式、字串等)
for 變數 in 可迭代物件 : 就像一般的 for 迴圈,用來逐一取出資料

2. 加上條件判斷
也可以在裡面加上 if 條件,例如:
https://ithelp.ithome.com.tw/upload/images/20251006/20178872vb3zQzWoAf.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251006/20178872d5MCV2x7MJ.png

  • range(10) → 會產生一個從 0 到 9 的整數序列
  • for i in range(10) → 代表會一個一個取出裡面的數字來用,所以第一次 i=0,然後 i=1,一直到 i=9
  • [i for i in range(10) if i % 2 == 0] → 意思是「把 range(10) 裡的每個 i 拿出來,但只要將偶數放進新列表」

3. 運算也能放進去
https://ithelp.ithome.com.tw/upload/images/20251006/201788722WY1ia8ARl.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251006/20178872zrIaiqV0W7.png

  • range(1, 6) → 會產生數字 1, 2, 3, 4, 5 (注意:range(1, 6) 不包含 6)
  • i ** 2 → ** 是「次方運算子」,意思是「i 的平方」,所以:
    當 i = 1 → 1 ** 2 = 1
    當 i = 2 → 2 ** 2 = 4
    當 i = 3 → 3 ** 2 = 9 ....
  • [i ** 2 for i in range(1, 6)] → 意思是「把 1 到 5 的平方值放進一個新列表」

4. 巢狀迴圈也能一行寫!
傳統寫法:
https://ithelp.ithome.com.tw/upload/images/20251006/20178872WUrbkjMg3d.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251006/20178872eA8Df0ZJjg.png

  • 外層迴圈 for x in [1, 2] : x 會依序取值,第一次:x = 1,第二次:x = 2
  • 內層迴圈 for y in [3, 4] : 每當外層的 x 改變,內層就會重新跑一遍,當 x = 1 時,y 依序是 3、4,當 x = 2 時,y 依序是 3、4

如果用推導式寫:
https://ithelp.ithome.com.tw/upload/images/20251006/20178872DIpbRPc3Nh.png

5. 文字處理應用
https://ithelp.ithome.com.tw/upload/images/20251006/20178872kpGHTuSqzN.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251006/20178872vN4jquUGXA.png

  • upper_words = [w.upper() for w in words]意思是:將 words 裡的每一個元素 w,把它變成大寫 (w.upper()),然後組成一個新的列表

6. 小練習
https://ithelp.ithome.com.tw/upload/images/20251006/20178872OycMQIF6PR.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251006/20178872nMtOMBKZfk.png
其實等同於前面學過的寫法:
https://ithelp.ithome.com.tw/upload/images/20251006/20178872dr2FHUK6TO.png


上一篇
Day21 : 字串處理技巧 – f-string、格式化、常用方法
下一篇
Day23 : 常用內建函式 – len、sum、enumerate、zip
系列文
學會 Python 不可怕:我每天學一點的 30 天筆記24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言