Python range function to resolve differences and enumerate

This article describes the Python range function parses the difference enumerate, the paper sample code described in great detail, has a certain reference value of learning for all of us to learn or work, a friend in need can refer to
enumerate more than the range in iteration flexible, generally try to use erumerate, exemplified below:

First look at the range of use

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)

Print Results:

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

Look at the usage 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))

The results are as follows:

1: beijing
2: shanghai
3: tianjing
4: wuhan
7: beijing
8: shanghai
9: tianjing
10: wuhan

In summary:

enumer function more concise wording, the index can be assigned to each element in the iteration
last to recommend a very wide python learning resource gathering, [click to enter] , here are my collection before learning experience, study notes, as well as experience first-line business, and calmed down to zero on the basis of the actual project data, we can at the bottom, leave a message, do not know to put forward, we will study together progress

Published 24 original articles · won praise 38 · views 20000 +

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104761816