【 Python 教學 】enumerate 函式介紹

Python 的 enumerate() 函式是一個非常有用的工具,特別是在處理迴圈時。這個函式可以將一個可迭代的對象(如列表、元組或字串)轉換為索引序列,同時列出資料和資料對應的索引值。這使得在迴圈中同時獲得元素和其對應索引變得簡單。

基本用法

enumerate() 函式的基本語法是 enumerate(iterable, start=0)。其中,iterable 是一個可迭代物件,如列表、元組、字串等。start 是可選參數,用來指定索引值的起始值,預設為 0。

假設有一個列表:fruits = ["apple", "banana", "cherry"]。使用 enumerate() 函式,可以這樣遍歷列表:

1
2
for index, fruit in enumerate(fruits):
print(index, fruit)

這將輸出:

1
2
3
0 apple
1 banana
2 cherry

如果指定 start 參數,例如 enumerate(fruits, start=1),則索引將從 1 開始計數。

使用範例

列表 (List)

假設我們有一個包含數字的列表,我們想要列印出每個數字及其索引:

1
2
3
numbers = [10, 20, 30, 40, 50]
for index, number in enumerate(numbers):
print(f"Index: {index}, Number: {number}")

輸出將是:

1
2
3
4
5
Index: 0, Number: 10
Index: 1, Number: 20
Index: 2, Number: 30
Index: 3, Number: 40
Index: 4, Number: 50

元組 (Tuple)

元組也可以使用 enumerate()。例如,我們有一個包含幾個城市名稱的元組:

1
2
3
cities = ("Taipei", "Kaohsiung", "Taichung")
for index, city in enumerate(cities):
print(f"Index: {index}, City: {city}")

輸出將是:

1
2
3
Index: 0, City: Taipei
Index: 1, City: Kaohsiung
Index: 2, City: Taichung

字串 (String)

對於字串,enumerate() 可以幫助我們獲得每個字元及其索引:

1
2
3
text = "Hello"
for index, char in enumerate(text):
print(f"Index: {index}, Character: {char}")

輸出將是:

1
2
3
4
5
Index: 0, Character: H
Index: 1, Character: e
Index: 2, Character: l
Index: 3, Character: l
Index: 4, Character: o

字典 (Dictionary)

雖然字典不是傳統意義上的序列,但我們仍然可以使用 enumerate() 來迭代它的鍵:

1
2
3
info = {"name": "John", "age": 30, "city": "New York"}
for index, key in enumerate(info):
print(f"Index: {index}, Key: {key}, Value: {info[key]}")

輸出將是:

1
2
3
Index: 0, Key: name, Value: John
Index: 1, Key: age, Value: 30
Index: 2, Key: city, Value: New York

在這些例子中,enumerate() 函式為我們提供了一種簡潔且高效的方式來迭代各種類型的可迭代物件,同時獲取它們的索引和值。

心得

Python 的 enumerate() 函式是處理迴圈和可迭代物件時的一個強大工具,它提高了程式碼的可讀性和效率。使用 enumerate() 的主要優點是它提供了一種簡潔的方式來獲取索引,並且比使用 range()len() 組合更為直觀和高效。它使程式碼更加清晰,易於理解和維護。

歡迎訂閱,獲取最新資訊、教學文章,一起變強。

評論