python enumerate函数_Python中enumerate函数用法详解
enumerate函數(shù)用于遍歷序列中的元素以及它們的下標(biāo),多用于在for循環(huán)中得到計(jì)數(shù),enumerate參數(shù)為可遍歷的變量,如 字符串,列表等
一般情況下對(duì)一個(gè)列表或數(shù)組既要遍歷索引又要遍歷元素時(shí),會(huì)這樣寫:for?i?in?range?(0,len(list)):
print?i?,list[i]
但是這種方法有些累贅,使用內(nèi)置enumerrate函數(shù)會(huì)有更加直接,優(yōu)美的做法,先看看enumerate的定義:def?enumerate(collection):
'Generates?an?indexed?series:?(0,coll[0]),?(1,coll[1])?...'
i?=?0
it?=?iter(collection)
while?1:
yield?(i,?it.next())
i?+=?1
enumerate會(huì)將數(shù)組或列表組成一個(gè)索引序列。使我們?cè)佾@取索引和索引內(nèi)容的時(shí)候更加方便如下:for?index,text?in?enumerate(list):
print?index?,text
代碼實(shí)例1:i?=?0
seq?=?['one',?'two',?'three']
for?element?in?seq:
print?i,?seq[i]
i?+=?1
0 one
1 two
2 three
代碼實(shí)例2:seq?=?['one',?'two',?'three']
for?i,?element?in?enumerate(seq):
print?i,?seq[i]
0 one
1 two
2 three
代碼實(shí)例3:for?i,j?in?enumerate('abc'):
print?i,j
0 a
1 b
2 c
總結(jié)
以上是生活随笔為你收集整理的python enumerate函数_Python中enumerate函数用法详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python怎么查看网页编码格式_怎么用
- 下一篇: websocket python爬虫_p