在迭代中enumerate比range更能灵活,一般情况下尽量用erumerate,下面举例说明:
先来看range的使用:
代码语言:javascript复制city_list = ['beijing', 'shanghai', 'tianjing', 'wuhan']
# 用range将元素打印出来
# 直接打印,不用range
for city in city_list:
print('this is %s' % city)
# 用下标打印
for i in range(len(city_list)):
city = city_list[i]
print('this is %s' % city)
# 以字典的方式打印
for i in range(len(city_list)):
city = city_list[i]
print('%s: %s' %(i 1,city)
打印结果:
代码语言:javascript复制this is beijing
this is shanghai
this is tianjing
this is wuhan
this is beijing
this is shanghai
this is tianjing
this is wuhan
1: beijing
2: shanghai
3: tianjing
4: wuhan
再看看enumera的用法:
代码语言:javascript复制for i,city in enumerate(city_list):
print('%s: %s' %(i 1,city))
# 也可以直接指定开始计数的值
for i,city in enumerate(city_list,7):
print('%s: %s' %(i,city))
结果如下:
代码语言:javascript复制1: beijing
2: shanghai
3: tianjing
4: wuhan
7: beijing
8: shanghai
9: tianjing
10: wuhan
综上:
enumer函数的写法更简洁,可以在迭代中给每个元素赋上索引
以上就是本文的全部内容,希望对大家的学习有所帮助。