Python內建函式之enumerate() 函式
阿新 • • 發佈:2019-10-09
enumerate() 函式屬於python的內建函式之一;
python內建函式參考文件:python內建函式
轉載自enumerate參考文件:python-enumerate() 函式
Python內建函式之enumerate() 函式
描述
enumerate() 函式用於將一個可遍歷的資料物件(如列表、元組或字串)組合為一個索引序列,同時列出資料和資料下標,一般用在 for 迴圈當中。
Python 2.3. 以上版本可用,2.6 新增 start 引數。
語法
以下是 enumerate() 方法的語法:
enumerate(sequence, [start=0])
引數
- sequence -- 一個序列、迭代器或其他支援迭代物件。
- start -- 下標起始位置。
返回值
返回 enumerate(列舉) 物件。
例項
以下展示了使用 enumerate() 方法的例項:
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) # 下標從 1 開始 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] >>> tuple(enumerate(seasons, start=1)) ((1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter'))
普通的for迴圈
>>>i = 0 >>> seq = ['one', 'two', 'three'] >>> for element in seq: ... print i, seq[i] ... i +=1 ... 0 one 1 two 2 three
for迴圈使用enumerate示例1
>>>seq = ['one', 'two', 'three']
>>>for temp in enumerate(seq): >>> print(temp) (0, 'one') (1, 'two') (2, 'three')
for迴圈使用enumerate示例2
>>>seq = ['one', 'two', 'three'] >>> for i, element in enumerate(seq): ... print (i, element) ... 0 one 1 two 2 three
&n