iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
Software Development

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

Day23 : 常用內建函式 – len、sum、enumerate、zip

  • 分享至 

  • xImage
  •  

在學 Python 的過程中,常常會看到一些「不用 import 就能用」的函式,這些就是內建函式,它們是 Python 預設提供的工具

1. len():計算長度
用來計算序列(如字串、列表、元組)中元素的個數
https://ithelp.ithome.com.tw/upload/images/20251007/20178872M1wSx6NEWt.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251007/20178872jB4V8SuLkD.png

  • len 是「length(長度)」的縮寫
  • len(words) 會回傳列表中有幾個項目
  • len("Hello") 會回傳字串中有幾個字元

2. sum():加總所有數值
對可迭代物件(例如列表或元組)中的數字進行加總
https://ithelp.ithome.com.tw/upload/images/20251007/20178872CdfiJMRjTW.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251007/20178872NSFzcnAFNC.png

  • sum(numbers) 會把列表裡的所有數字加起來
  • 可以加上第二個參數作為「起始值」:
    https://ithelp.ithome.com.tw/upload/images/20251007/20178872T3OljtHSJG.png
    sum() 其實有兩個參數:sum(iterable, start)
    iterable:要加總的數字集合(像是 list、tuple)
    start:起始值(可選,預設是 0)
    sum([1, 2, 3], 10) 的意思是,給了起始值 10,所以會 :
    從 10 開始,加上 1 → 11
    再加上 2 → 13
    再加上 3 → 16

3. enumerate():同時取得「索引」與「內容」
在使用 for 迴圈時,enumerate()可以讓你同時拿到:
每個項目的索引(index)
每個項目的值(value)
https://ithelp.ithome.com.tw/upload/images/20251007/20178872zCA0SmwcjI.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251007/201788727QU20l4RsA.png

  • 一般 for fruit in fruits 只會到內容(fruit)
  • 如果使用 enumerate() 的話,就會「附上編號」,通常預設編號會從 0 開始,但也可以改成從 1開始:
    https://ithelp.ithome.com.tw/upload/images/20251007/20178872dT17VZtNyy.png
    那麼結果就會輸出
    https://ithelp.ithome.com.tw/upload/images/20251007/20178872sNnoXsmIhY.png

4. zip():把多個序列「一一配對」
https://ithelp.ithome.com.tw/upload/images/20251007/20178872K0VBrL5CQg.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251007/20178872DOjNG3ItcB.png

  • zip() 會「拉鍊式」地把兩個(或多個)列表配對在一起
  • 第一個元素配第一個,第二個配第二個,以此類推

結果可以轉成列表:
https://ithelp.ithome.com.tw/upload/images/20251007/20178872Gp7gjoO58O.png
那麼結果就會輸出
https://ithelp.ithome.com.tw/upload/images/20251007/20178872WnpIyh8hjs.png

5. 補充:搭配使用
可以結合前面的函式:
https://ithelp.ithome.com.tw/upload/images/20251007/201788720KbkjiyCs1.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251007/20178872JGR3WmeBtE.png

  • zip(names, scores) : zip() 會把多個「可迭代物件」(像是 list)一一配對起來
  • enumerate() 會在迴圈中自動幫每個元素編號,這裡的 start=1 代表從 1 開始編號(預設是從 0)
  • for i, (name, score) in ... : 是同時解包兩層的資料結構,i → enumerate 給的編號,(name, score) → zip 給的配對內容,也就是:
    第 1 次:i=1, name="Amy", score=98
    第 2 次:i=2, name="Bob", score=56
    第 3 次:i=3, name="Frank", score=73

上一篇
Day22 : 列表推導式 & 簡化技巧 – 一行寫出迴圈
下一篇
Day24 : 基礎物件導向概念 – class、屬性、方法
系列文
學會 Python 不可怕:我每天學一點的 30 天筆記24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言