在迭代中enumerate比range更能灵活,一般情况下尽量用erumerate,下面举例说明:
先来看range的使用:
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)
打印结果:
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的用法:
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))
结果如下:
1: beijing 2: shanghai 3: tianjing 4: wuhan 7: beijing 8: shanghai 9: tianjing 10: wuhan
综上:
enumer函数的写法更简洁,可以在迭代中给每个元素赋上索引
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/181577/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)