Python enumerate 用法

六月ゝ 毕业季﹏ 提交于 2020-01-02 01:45:59

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 查看用户
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!