enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

语法:
enumerate(sequence, [start=0])

参数说明:
sequence -- 一个序列、迭代器或其他支持迭代对象。
start -- 下标起始位置。

例子一:

seq = [\'one\', \'two\', \'three\']
for i, item in enumerate(seq):
    print(i, item)

# 运行结果:
0 one
1 two
2 three

例子二: 可做菜单

permission_list = [
    {\'caption\': \'添加用户\', \'func\': \'add\'},
    {\'caption\': \'删除用户\', \'func\': \'delete\'},
    {\'caption\': \'查看用户\', \'func\': \'fetch\'}
]

for index, item in enumerate(permission_list, 1):
    print(index, item[\'caption\'])

# 运行结果:
1 添加用户
2 删除用户
3 查看用户
收藏 打印