Python內置函數之enumerate() 函數


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM