这篇文章主要介绍了Python range与enumerate函数区别解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
在迭代中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&