前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 函数 enumerate

python 函数 enumerate

作者头像
py3study
发布2020-01-13 20:33:11
4910
发布2020-01-13 20:33:11
举报
文章被收录于专栏:python3python3

python中enumerate方法,返回一个enumerate类型。参数一般是可以遍历的的东西,比如列表,字符串什么的。

python文档中是这么说的:

enumerate(sequence, [start=0])

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which sup-

ports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing

a count (from start which defaults to 0) and the corresponding value obtained from iterating over iter-

able. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2,

seq[2]), .... 

For example:

>>> for i, season in enumerate([’Spring’, ’Summer’, ’Fall’, ’Winter’]):

...

 print i, season

0 Spring

1 Summer

2 Fall

3 Winter

个人理解是:当你既需要下标,又需要内容时可以用这个函数来解决

以下是我写的例子:

代码语言:javascript
复制
# 字符串的使用
value_1 = 'fdahkjlzkjfhaqf'
index = 0
for i in value_1:       # 不使用enumerate函数
    print index, i
    index += 1

for index, value in enumerate(value_1):   # 使用enumerate函数
    print index, value

# 列表的使用
value_2 = ['a', 'b', 'c', 'd']
index = 0
for i in value_2:       # 不使用enumerate函数
    print index, i
    index += 1
for index, value in enumerate(value_2):     # 使用enumerate函数
    print index, value
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档