如何在 Python 中使用枚舉(帶索引循環)

了解如何在 Python 中使用 enumerate() 函式。循環使用乾淨範例的清單時取得索引和值。

在編輯器中嘗試此解決方案

概述

當迭代列表、元組或字串時,您通常需要追蹤每個項目的當前索引以及項目本身。常見的初學者模式是使用手動遞增的單獨計數器變量,或使用“range(len(my_list))”透過索引進行迭代。然而,Python 提供了一個更優雅、Python 化的內建解決方案:「enumerate()」函數。

enumerate() 函數將任何可迭代物件作為參數並傳回一個枚舉對象,該物件產生索引值元組對。透過在「for」迴圈中使用元組解包,您可以同時提取索引和項目。這完全消除了對手動計數器變數和索引括號的需要,使您的程式碼顯著簡潔,並且不太容易出現相差一錯誤。

預設情況下,「enumerate()」從「0」開始計算索引。但是,您可以使用可選的“start”關鍵字參數(例如“enumerate(items, start=1)”)傳遞自訂起始索引。當向人類使用者顯示清單編號時,這非常有用,因為人們通常希望清單從 1 而不是 0 開始計數。

程式碼和執行輸出

此腳本演示了使用 enumerate 迭代列表以獲取從 0 和 1 開始的索引項對。

use_enumerate.py
在編輯器中嘗試
fruits = ["apple", "banana", "cherry"]

# 1. Standard enumeration (starts at 0)
print("--- Standard Enumeration ---")
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

# 2. Enumeration starting at a custom index (e.g., 1)
print("\n--- Starting at 1 ---")
for num, fruit in enumerate(fruits, start=1):
    print(f"Item #{num}: {fruit}")
端子輸出
--- Standard Enumeration ---
Index 0: apple
Index 1: banana
Index 2: cherry

--- Starting at 1 ---
Item #1: apple
Item #2: banana
Item #3: cherry

逐步實施

  • 將列表(或任何可迭代物件)傳遞給內建 enumerate() 函數。
  • 使用 for index, value in enumerate(list) 語法在 for 迴圈中解壓縮傳回的元組。
  • 提供啟動參數(例如,start=1)以修改初始索引計數器值。

常見問題解答

enumerate() 是否修改了原始清單?

不, enumerate() 傳回一個惰性迭代器對象,並使原始列表完全不被修改。

我可以將 enumerate() 與字典一起使用嗎?

是的,但是直接迭代字典會產生它的鍵。若要迭代索引鍵值,請使用: for i, (k, v) in enumerate(my_dict.items()):。

相關主題

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。