当前位置:首页 >> 脚本专栏

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+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函数的写法更简洁,可以在迭代中给每个元素赋上索引

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。