Python3 enumerate() 函數(shù)

2019-03-25 14:02 更新

Python3 enumerate() 函數(shù)

Python3 內置函數(shù) Python3 內置函數(shù)

描述

Python3 enumerate() 函數(shù)用于將一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串)組合為一個索引序列,同時列出數(shù)據(jù)和數(shù)據(jù)下標,一般用在 for 循環(huán)當中。

語法

以下是 enumerate() 方法的語法:

enumerate(sequence, [start=0])

參數(shù)

  • 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')]

普通的for循環(huán):

>>>i = 0
>>>seq = ['one', 'two', 'three']
>>>for element in seq:
... print(i, seq[i])
... i += 1
...
0 one
1 two
2 three

for循環(huán)使用enumerate:

>>>seq = ['one', 'two', 'three']
>>>for i, element in enumerate(seq):
... print(i, seq[i])
...
0 one
1 two
2 three
>>>

Python3 內置函數(shù) Python3 內置函數(shù)

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號