Python enumerate() 函式



Python enumerate() 函式用於訪問可迭代物件中的每個專案。此函式接受一個可迭代物件並將其作為列舉物件返回。它還為每個可迭代項新增一個計數器,以簡化迭代過程。

計數器充當可迭代項的每個專案的索引,有助於遍歷。請記住,可迭代物件是一個允許我們透過迭代訪問其專案的物件。

enumerate() 函式是 內建函式 之一,不需要匯入任何模組。

語法

以下是 python enumerate() 函式的語法。

enumerate(iterable, startIndex)

引數

以下是 python enumerate() 函式的引數:

  • iterable - 此引數表示一個可迭代物件,例如 列表元組字典集合

  • startIndex - 它指定可迭代物件的起始索引。這是一個可選引數,其預設值為 0。

返回值

python enumerate() 函式返回列舉物件。

enumerate() 函式示例

練習以下示例以瞭解如何在 Python 中使用 enumerate() 函式

示例:enumerate() 函式的使用

以下是 Python enumerate() 函式的一個示例。在此,我們建立了一個列表,並嘗試使用 enumerate() 函式訪問其每個元素。

fruitLst = ["Grapes", "Apple", "Banana", "Kiwi"]
newLst = list(enumerate(fruitLst))
print("The newly created list:")
print(newLst)

執行上述程式後,將生成以下輸出:

The newly created list:
[(0, 'Grapes'), (1, 'Apple'), (2, 'Banana'), (3, 'Kiwi')]

示例:帶有 'start' 引數的 enumerate() 函式

如果我們為列舉指定起始索引,則索引號將從指定的索引值開始。在下面的程式碼中,我們將 1 指定為起始索引。

fruitLst = ["Grapes", "Apple", "Banana", "Kiwi"]
newLst = list(enumerate(fruitLst, start=1))
print("The newly created list:")
print(newLst)

以下是執行上述程式獲得的輸出:

The newly created list:
[(1, 'Grapes'), (2, 'Apple'), (3, 'Banana'), (4, 'Kiwi')]

示例:帶有 for 迴圈的 enumerate() 函式

enumerate() 函式也可以與 for 迴圈 結合使用,以訪問列表中的元素,如下面的示例所示。

fruitLst = ["Grapes", "Apple", "Banana", "Kiwi"]
print("The newly created list:")
for index, fruit in enumerate(fruitLst):
   print(f"Index: {index}, Value: {fruit}")

執行上述程式後,將獲得以下輸出:

The newly created list:
Index: 0, Value: Grapes
Index: 1, Value: Apple
Index: 2, Value: Banana
Index: 3, Value: Kiwi

示例:帶有元組列表的 enumerate() 函式

在下面的示例中,我們正在建立一個元組列表,並應用 enumerate() 函式來顯示列表的所有元素。

fruits = [(8, "Grapes"), (10, "Apple"), (9, "Banana"), (12, "Kiwi")]
for index, (quantity, fruit) in enumerate(fruits):
   print(f"Index: {index}, Quantity: {quantity}, Fruit: {fruit}")

執行上述程式後,將顯示以下輸出:

Index: 0, Quantity: 8, Fruit: Grapes
Index: 1, Quantity: 10, Fruit: Apple
Index: 2, Quantity: 9, Fruit: Banana
Index: 3, Quantity: 12, Fruit: Kiwi
python_built_in_functions.htm
廣告