在 Python 的世界裡,序列(Sequence)是一種非常重要的資料結構。它指的是一系列有序排列的資料集合,例如:串列 (list)、元組 (tuple) 和字串 (string) 等。
掌握如何有效率地操作這些序列,是每個 Python 開發者的必備技能。幸運的是,Python 內建了許多強大的函式,讓您無需額外安裝,就能輕鬆處理序列資料。
本文將聚焦於五個最常用的序列操作函式,並透過實戰範例,帶您一舉掌握它們的用法。
1. len():測量長度
len() 函式的任務非常單純:計算序列中元素的數量。無論您要計算串列有多少個項目、字串有多少個字元,len() 都能為您提供答案。
- 適用對象: 串列 (list)、元組 (tuple)、字串 (string)、字典 (dict)、集合 (set) 等。
- 基本用法: len(<序列變數>)
# 計算串列的長度
my_list = [10, 20, 30, 40, 50]
print(f"串列的長度是:{len(my_list)}") # 輸出:5
# 計算字串的長度
my_string = "Hello, Python!"
print(f"字串的長度是:{len(my_string)}") # 輸出:14
2. max() 與 min():尋找最大值與最小值
max() 與 min() 函式用於尋找序列中的最大值和最小值。它們會根據元素的類型(如數字、字元)進行比較。
- 適用對象: 串列 (list)、元組 (tuple)、字串 (string) 等。
- 基本用法: max(<序列變數>) 和 min(<序列變數>)
# 在數字串列中尋找最大值與最小值
scores = [88, 95, 76, 92, 85]
highest_score = max(scores)
lowest_score = min(scores)
print(f"最高分是:{highest_score}") # 輸出:95
print(f"最低分是:{lowest_score}") # 輸出:76
# 在字串中尋找最大值與最小值(按字母順序)
my_word = "python"
print(f"字母順序最大的字元是:{max(my_word)}") # 輸出:y
print(f"字母順序最小的字元是:{min(my_word)}") # 輸出:h
3. sum():加總數值
sum() 函式可以快速計算序列中所有數值元素的總和。這對於數據分析和快速計算非常有用。
- 適用對象: 包含數字型別(int 或 float)的序列,如串列、元組。
- 基本用法: sum(<序列變數>)
# 計算一個月內的銷售額總和
sales = [1200.50, 850.75, 2300.00, 1550.25]
total_sales = sum(sales)
print(f"本月總銷售額是:{total_sales}") # 輸出:5906.5
# 計算一個學生的總分
quiz_scores = [90, 88, 95, 82]
total_score = sum(quiz_scores)
print(f"總分是:{total_score}") # 輸出:355
4. sorted():排序新序列
sorted() 函式是一個功能強大的排序工具。與串列的 .sort() 方法不同,sorted() 不會改變原始序列,而是回傳一個全新的、已排序的串列。
這讓原始資料保持不變,非常適合需要同時保留原始順序與排序後順序的應用場景。
- 適用對象: 任何可迭代的物件,包括串列、元組、字串等。
- 基本用法: sorted(<序列變數>)。
- 進階用法: 您可以使用 reverse=True 參數來進行降序排序。
# 對數字串列進行升序排序
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(f"原始串列:{numbers}") # 輸出:[3, 1, 4, 1, 5, 9, 2]
print(f"排序後的串列:{sorted_numbers}") # 輸出:[1, 1, 2, 3, 4, 5, 9]
# 對字串進行降序排序
words = ["apple", "banana", "orange"]
sorted_words_desc = sorted(words, reverse=True)
print(f"降序排序的結果:{sorted_words_desc}") # 輸出:['orange', 'banana', 'apple']
綜合實戰:數據分析初體驗
讓我們將這五個函式結合起來,對一組學生成績進行簡單的數據分析。
student_scores = [85, 92, 78, 95, 60, 88, 70, 92]
# 1. 班上有多少人?
num_students = len(student_scores)
print(f"班級總人數:{num_students}")
# 2. 最高分與最低分各是多少?
highest = max(student_scores)
lowest = min(student_scores)
print(f"最高分:{highest}")
print(f"最低分:{lowest}")
# 3. 總分與平均分是多少?
total_score = sum(student_scores)
average_score = total_score / num_students
print(f"總分:{total_score}")
print(f"平均分:{average_score:.2f}") # .2f 表示保留兩位小數
# 4. 看看所有分數排序後是怎樣?
sorted_scores = sorted(student_scores)
print(f"分數由低到高排序:{sorted_scores}")
透過這些實用的內建函式,您能夠用最少的程式碼,快速地從序列資料中提取有用的資訊,這也正是 Python 簡潔且強大的魅力所在。