Python3中enumerate内置函数使用方式:
enumerate(sequence, [start=0])
enumerate多用于在for循环中得到计数
Note1:
sequence是序列,序列可以是列表,字符串,
# 列表
direction_list = ['East', 'South', 'West', 'North']
# 字符串
direction_string = 'East'
flag = True
# flag = False
if flag:
for i in enumerate(direction_list):
print(i)
else:
for i in enumerate(direction_string):
print(i)
Note2:
for后面的位置可以返回不同的东西,如下:
# 列表
direction_list = ['East', 'South', 'West', 'North']
# 字符串
direction_string = 'East'
flag = True
# flag = False
if flag:
for i in enumerate(direction_list):
print(i)
for (index, derection) in enumerate(direction_list):
print(index, derection)
else:
for i in enumerate(direction_string):
print(i)
for (index, derection) in enumerate(direction_string):
print(index, derection)
Note3:
参数start是认为想要标记数据的起始位置,默认从0标记。想要列表索引为0的标记为1,就是start=1。想要字符串索引为0的标记为2,start=2。
# 列表
direction_list = ['East', 'South', 'West', 'North']
# 字符串
direction_string = 'East'
flag = True
# flag = False
if flag:
for (index_0, derection_0) in enumerate(direction_list):
print(index_0, derection_0)
for (index_1, derection_1) in enumerate(direction_list, start=1):
print(index_1, derection_1)
for (index_2, derection_2) in enumerate(direction_list, start=2):
print(index_2, derection_2)
else:
for (index_0, derection_0) in enumerate(direction_string ):
print(index_0, derection_0)
for (index_1, derection_1) in enumerate(direction_string , start=1):
print(index_1, derection_1)
for (index_2, derection_2) in enumerate(direction_string , start=2):
print(index_2, derection_2)
把代码敲一下,运行一下,看一下结果,就知道enumerate函数的用法了。还有一些高级用法,我还没碰到,碰到了再添加。
文章最后有微信公众号:惟CPP,欢迎关注,一起交流学习进步~