常用內建函式#

Python 內建函式(built-in functions)不需要 import,可以直接使用。本篇介紹幾個處理序列資料時最常用的函式。


zip()#

zip() 將多個可迭代物件逐元素配對,回傳一個迭代器,每個元素是一個 tuple:

1
2
3
4
5
6
7
8
9
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

for name, score in zip(names, scores):
    print(f"{name}{score} 分")

# Alice:85 分
# Bob:92 分
# Charlie:78 分

配對多個序列#

1
2
3
4
5
6
names  = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
cities = ["Taipei", "Kaohsiung", "Taichung"]

for name, score, city in zip(names, scores, cities):
    print(f"{name}{city}):{score} 分")

長度不同時#

zip()最短 的序列為準,多餘的元素會被忽略。若需要填補缺少的值,改用 itertools.zip_longest()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from itertools import zip_longest

list1 = [1, 2, 3]
list2 = ["a", "b"]

print(list(zip(list1, list2)))
# [(1, 'a'), (2, 'b')]

print(list(zip_longest(list1, list2, fillvalue="?")))
# [(1, 'a'), (2, 'b'), (3, '?')]

建立字典#

1
2
3
4
5
6
keys   = ["name", "age", "city"]
values = ["Alice", 25, "Taipei"]

person = dict(zip(keys, values))
print(person)
# {'name': 'Alice', 'age': 25, 'city': 'Taipei'}

解壓縮(Unzip)#

zip(*iterable) 還原原本的序列:

1
2
3
4
5
pairs = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]

names, scores = zip(*pairs)
print(names)   # ('Alice', 'Bob', 'Charlie')
print(scores)  # (85, 92, 78)

轉置矩陣#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

transposed = list(zip(*matrix))
for row in transposed:
    print(row)

# (1, 4, 7)
# (2, 5, 8)
# (3, 6, 9)

enumerate()#

enumerate() 在迭代時同時取得 索引 ,避免手動維護計數器:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fruits = ["apple", "banana", "cherry"]

# 傳統寫法
for i in range(len(fruits)):
    print(i, fruits[i])

# 使用 enumerate(更 Pythonic)
for i, fruit in enumerate(fruits):
    print(i, fruit)

# 0 apple
# 1 banana
# 2 cherry

指定起始索引#

1
2
3
4
5
6
for i, fruit in enumerate(fruits, start=1):
    print(f"第 {i} 個:{fruit}")

# 第 1 個:apple
# 第 2 個:banana
# 第 3 個:cherry

找出符合條件的索引#

1
2
3
4
scores = [72, 85, 60, 91, 55, 88]

failing = [i for i, s in enumerate(scores) if s < 60]
print(failing)  # [4](索引 4 的分數 55 不及格)

map()#

map() 對序列中的每個元素套用函式,回傳一個迭代器:

1
2
3
4
5
6
7
numbers = [1, 2, 3, 4, 5]

squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# 等同於串列推導式(推薦)
squares = [x ** 2 for x in numbers]

搭配具名函式#

1
2
3
4
5
6
def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

temps_c = [0, 20, 37, 100]
temps_f = list(map(celsius_to_fahrenheit, temps_c))
print(temps_f)  # [32.0, 68.0, 98.6, 212.0]

同時處理多個序列#

1
2
3
4
5
a = [1, 2, 3]
b = [10, 20, 30]

result = list(map(lambda x, y: x + y, a, b))
print(result)  # [11, 22, 33]

filter()#

filter() 篩選出符合條件的元素,回傳一個迭代器:

1
2
3
4
5
6
7
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# 等同於串列推導式(推薦)
evens = [x for x in numbers if x % 2 == 0]

篩選非空字串#

1
2
3
words = ["hello", "", "world", "", "python"]
non_empty = list(filter(None, words))  # None 表示過濾掉 falsy 的值
print(non_empty)  # ['hello', 'world', 'python']

sorted() 與 key#

sorted() 回傳排序後的新串列,key 參數可自訂排序規則:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
words = ["banana", "apple", "cherry", "kiwi"]

# 預設字母順序
print(sorted(words))
# ['apple', 'banana', 'cherry', 'kiwi']

# 依長度排序
print(sorted(words, key=len))
# ['kiwi', 'apple', 'banana', 'cherry']

# 由大到小
print(sorted(words, key=len, reverse=True))
# ['banana', 'cherry', 'apple', 'kiwi']

對字典串列排序#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
students = [
    {"name": "Alice",   "score": 85, "age": 20},
    {"name": "Bob",     "score": 92, "age": 22},
    {"name": "Charlie", "score": 85, "age": 21},
]

# 依分數由高到低排序
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
for s in by_score:
    print(f"{s['name']}{s['score']}")

# Bob:92
# Alice:85
# Charlie:85

多條件排序#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 分數相同時,依年齡由小到大
by_score_then_age = sorted(
    students,
    key=lambda s: (-s["score"], s["age"])
)
for s in by_score_then_age:
    print(f"{s['name']}{s['score']}{s['age']} 歲")

# Bob:92,22 歲
# Alice:85,20 歲
# Charlie:85,21 歲

any() 與 all()#

any():有任一元素為 True 就回傳 True#

1
2
3
4
5
6
7
scores = [72, 85, 60, 91, 55]

# 有人滿分嗎?
print(any(s == 100 for s in scores))  # False

# 有人不及格嗎?
print(any(s < 60 for s in scores))   # True

all():所有元素都為 True 才回傳 True#

1
2
3
4
5
6
# 所有人都及格嗎?
print(all(s >= 60 for s in scores))  # False

# 驗證所有輸入都是正整數
inputs = [3, 7, 2, 9]
print(all(isinstance(x, int) and x > 0 for x in inputs))  # True

min() 與 max() 搭配 key#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
students = [
    {"name": "Alice",   "score": 85},
    {"name": "Bob",     "score": 92},
    {"name": "Charlie", "score": 78},
]

best   = max(students, key=lambda s: s["score"])
worst  = min(students, key=lambda s: s["score"])

print(f"最高分:{best['name']}{best['score']})")    # Bob(92)
print(f"最低分:{worst['name']}{worst['score']})")  # Charlie(78)

綜合範例:成績分析#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
students = [
    ("Alice",   [85, 92, 78]),
    ("Bob",     [70, 88, 95]),
    ("Charlie", [60, 55, 72]),
]

# 計算每人平均,並加入結果
with_avg = [
    (name, scores, round(sum(scores) / len(scores), 1))
    for name, scores in students
]

# 依平均由高到低排序
ranked = sorted(with_avg, key=lambda x: x[2], reverse=True)

print("=== 成績排名 ===")
for rank, (name, scores, avg) in enumerate(ranked, start=1):
    status = "及格" if avg >= 60 else "不及格"
    print(f"第 {rank} 名|{name}|平均 {avg}{status}")

# 全部及格嗎?
all_pass = all(avg >= 60 for _, _, avg in with_avg)
print(f"\n全部及格:{all_pass}")

輸出:

=== 成績排名 ===
第 1 名|Alice|平均 85.0|及格
第 2 名|Bob|平均 84.3|及格
第 3 名|Charlie|平均 62.3|及格

全部及格:True