10 個 Python 開發者每天都在用的內建函式

10 個 Python 開發者每天都在用的內建函式
一台筆記型電腦螢幕上顯示著 Python 標誌與程式碼,象徵 Python 的內建功能。

對於剛踏入 Python 世界的初學者來說,學習語法與函式庫似乎永無止境。但您會發現,許多專業的 Python 開發者在日常工作中,其實都頻繁使用一些看似基礎,卻能大幅提升效率的內建函式 (Built-in Functions)。

這些函式是 Python 語言的核心,您無需 import 任何東西,就能直接使用。它們不僅讓程式碼更簡潔,也更具可讀性。

本文將為您解析 10 個開發者們每天都在使用的內建函式,掌握它們將幫助您寫出更專業、更「Pythonic」的程式碼。

1. enumerate():同時取得索引與值

當您需要遍歷一個序列(如列表或元組),並且同時需要知道每個元素的位置(索引)與內容時,enumerate() 是您的最佳幫手。

它能將可迭代的物件轉換為一個由 (索引, 值) 組成的元組序列,避免您手動維護一個計數器。

fruits = ['apple', 'banana', 'cherry']

# 傳統方法:需要手動建立索引變數
i = 0
for fruit in fruits:
    print(f"Index {i}: {fruit}")
    i += 1

print("-" * 20)

# 使用 enumerate() 的 Pythonic 方法
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

2. zip():打包多個序列

zip() 函式能將多個序列(例如列表)中的對應元素打包成一個個元組,讓您可以同時遍歷它們。這在處理相關聯資料時特別方便。

names = ['Alice', 'Bob', 'Charlie']
scores = [95, 88, 72]

# 將兩個列表打包,同時遍歷
for name, score in zip(names, scores):
    print(f"{name}'s score is {score}")

3. map():對每個元素執行相同操作

map() 函式可以對序列中的每個元素套用一個指定的函式,並回傳一個結果的迭代器(iterator)。它通常用於簡化迴圈,特別是在需要對每個元素進行轉換時。

numbers = [1, 2, 3, 4]

# 將每個數字轉換為字串
string_numbers = list(map(str, numbers))
print(string_numbers)
# 輸出:['1', '2', '3', '4']

# 透過 lambda 函式將每個數字乘以 2
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers)
# 輸出:[2, 4, 6, 8]

4. filter():過濾符合條件的元素

filter() 函式能根據一個指定的函式,篩選出序列中符合條件的元素,並回傳一個迭代器。這讓您可以快速建立新的列表,而無需寫冗長的 if 判斷式。

ages = [15, 22, 18, 25, 17]

# 過濾出所有成年人的年齡(>= 18)
adult_ages = list(filter(lambda age: age >= 18, ages))
print(adult_ages)
# 輸出:[22, 18, 25]

5. all() 與 any():快速布林判斷

這兩個函式能快速判斷一個可迭代物件中的所有或任一元素是否滿足布林條件。

  • all():如果所有元素都為真,則回傳 True
  • any():如果任一元素為真,則回傳 True
boolean_list1 = [True, True, True]
boolean_list2 = [True, False, True]

print(f"所有元素都為真嗎?{all(boolean_list1)}") # 輸出:True
print(f"所有元素都為真嗎?{all(boolean_list2)}") # 輸出:False

print(f"有任何一個元素為真嗎?{any(boolean_list1)}") # 輸出:True
print(f"有任何一個元素為真嗎?{any(boolean_list2)}") # 輸出:True

6. isinstance():檢查物件類型

在處理來自不同來源的資料時,isinstance() 是個非常實用的函式。它能檢查一個物件是否為指定類型或其子類的實例,避免程式因為型別錯誤而崩潰。

my_data = "Hello"
my_number = 123

print(isinstance(my_data, str))   # 輸出:True
print(isinstance(my_number, int)) # 輸出:True
print(isinstance(my_data, int))   # 輸出:False

7. abs():取絕對值

abs() 函式用於取得一個數字的絕對值。這在計算數值差異或距離時非常有用。

distance1 = 10 - 25
distance2 = 25 - 10

print(f"絕對距離:{abs(distance1)}") # 輸出:15
print(f"絕對距離:{abs(distance2)}") # 輸出:15

8. round():四捨五入

round() 函式能將一個數字四捨五入到指定的小數位數。

pi = 3.1415926

print(f"四捨五入到小數點後兩位:{round(pi, 2)}") # 輸出:3.14
print(f"四捨五入到小數點後三位:{round(pi, 3)}") # 輸出:3.142

9. help():取得函式說明

當您忘記某個函式的用法時,help() 是一個強大的即時查詢工具。它能直接在您的開發環境中顯示函式的詳細說明、參數與回傳值。

help(print)
# 執行後,會顯示 print() 函式的詳細使用說明

10. dir():列出物件屬性與方法

dir() 函式可以列出一個物件的所有屬性與方法。當您拿到一個新物件,不確定它有哪些可用功能時,dir() 是您的最佳偵測工具。

my_list = [1, 2, 3]

# 列出 my_list 擁有的所有方法與屬性
print(dir(my_list))
# 輸出:['__add__', '__class__', ..., 'append', 'clear', 'copy', ...]
較新的 較舊