enumerate()使用

enumerate在字典上是枚举、列举的意思;对于一个可迭代的/可遍历的对象(如列表和字符串),enumerate可以对其获得索引和值,常用于for循环中得到计数。

1、对于一个列表,既要遍历索引又要遍历元素时

test = ["","","一个","测试"]
for i in range(len(test)):
    print(i,test[i])

2、但是可以使用enumerate函数使其更为简洁

test = ["","","一个","测试"]
for index,item in enumerate(test):
    print(index,item)
#结果是

0 这
1 是
2 一个
3 测试

3、还可以接受第二个参数来指定索引起始值

test = ["","","一个","测试"]
for index,item in enumerate(test,1):
    print(index,item)

#结果是
123 一个
4 测试

 

posted on 2018-02-03 16:39  告辞  阅读(265)  评论(0)    收藏  举报

导航