美文网首页
python之 enumerate()函数

python之 enumerate()函数

作者: _沉梦昂志 | 来源:发表于2018-04-17 21:57 被阅读0次

1. enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用来for循环中

例子:

>>>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循环:

>>>i = 0

>>> seq = ['one', 'two', 'three']

>>> for element in seq:

...    print i, seq[i]

...    i +=1

... 

0 one

1 two

2 three


for循环使用enumerate:

>>>seq = ['one', 'two', 'three']

>>> for i, element in enumerate(seq):

...    print i, seq[i]

... 

0 one

1 two

2 three

相关文章

网友评论

      本文标题:python之 enumerate()函数

      本文链接:https://www.haomeiwen.com/subject/enxmkftx.html