在處理列表、元組、字符串等有順序的數據類型時,有時需要訪問元素本身以及它們的索引值。在Python中,可以使用enumerate()函數輕鬆地完成這個任務。
一、enumerate()函數的基本使用
enumerate()函數可以在for循環中同時迭代元素本身和其對應的索引值:
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(f'Index: {index}, Fruit: {fruit}')
運行結果為:
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: orange
從輸出結果中可以看出,enumerate()函數將每個元素和其對應的索引組成一個元組,然後返回一個迭代器。
如果希望從非零索引開始枚舉,則可以傳遞一個start參數:
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits, start=1):
print(f'Index: {index}, Fruit: {fruit}')
運行結果為:
Index: 1, Fruit: apple
Index: 2, Fruit: banana
Index: 3, Fruit: orange
二、enumerate()函數的高級用法
1. 枚舉多個序列的元素
雖然enumerate()函數最經常用於枚舉單個序列,但它也可以枚舉多個序列的元素。在這種情況下,enumerate()將返回一個元組,其中包含在所有序列中具有相同索引的元素。
fruits = ['apple', 'banana', 'orange']
prices = [1.2, 3.3, 2.5]
for index, (fruit, price) in enumerate(zip(fruits, prices)):
print(f'Index: {index}, Fruit: {fruit}, Price: {price}')
運行結果為:
Index: 0, Fruit: apple, Price: 1.2
Index: 1, Fruit: banana, Price: 3.3
Index: 2, Fruit: orange, Price: 2.5
上面的代碼中,zip()函數將兩個序列打包成一個元組,並在每次迭代中傳遞一個元組到enumerate()函數中。
2. 以不同的步長枚舉序列的元素
有時,需要從序列中以不同的步長枚舉元素。在這種情況下,可以使用itertools模塊的islice()函數來實現。
import itertools
fruits = ['apple', 'banana', 'orange', 'grape', 'pineapple']
step = 2
for index, fruit in enumerate(itertools.islice(fruits, 0, None, step)):
print(f'Index: {index}, Fruit: {fruit}')
運行結果為:
Index: 0, Fruit: apple
Index: 1, Fruit: orange
Index: 2, Fruit: pineapple
在上面的代碼中,islice()函數選擇從序列的第一個元素開始,每隔step個元素就選擇一次。使用None作為islice()的結束參數來選擇序列的所有剩餘元素。
三、總結
Python的enumerate()函數是一個非常有用的函數,可以幫助我們輕鬆追蹤序列的元素索引。除了基本用法之外,我們還可以使用enumerate()函數來枚舉多個序列的元素,並以不同的步長枚舉序列的元素。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/232196.html