在python中,尽量避免在不需要的地方使用range函数来生成列表序列号。但是如果要在列出的元素旁边加上数字序列号怎么办呢?这时就可以使用enumerate来生成列表序列号。
enumerate函数使用一个可迭代的对象(例如一个列表)作为参数,并生成另一个可迭代的对象,即一系列元组,每个元组都具有以下形式:
(num,item)
str_list=["test1","test2","test3"]
new_list=list(enumerate(str_list,start=1))
print(new_list)
输出:
[(1, ‘test1’), (2, ‘test2’), (3, ‘test3’)]
#enumerate(iter,start=0)
#start参数默认值为0,可以不写,即索引号从0开始
num_list = [1,2,3,4,5,6,7,8]
for index,val in enumerate(num_list,start=0):
print(index,val,sep=".")
输出:
0.1
1.2
2.3
3.4
4.5
5.6
6.7
7.8
num_list = [1,2,3,4,5,6,7,8]
for index,val in enumerate(num_list,start=1):
print(index,val,sep=".")
输出:
1.1
2.2
3.3
4.4
5.5
6.6
7.7
8.8