range與enumerate的區別

Tynam.Yang發表於2018-03-29

在迭代中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函式的寫法更簡潔,可以在迭代中給每個元素賦上索引


相關文章