enumerate() 函数的作用是将一个可遍历或可迭代的对象按照设置的序号组成一个索引序列。语法格式如下:
enumerate(iterable[,start])
说明:
(1)iterable:表示一个序列、迭代器或其他支持迭代的对象。
(2)start:用于设置下标的起始位置,默认为0。
(3)函数返回一个列表(类型为:enumerate),列表由新生成的序号和原有数据组成的元组构成。
例如:
lang = ["java","go","c","vb","c++"]
list1 = enumerate(lang,1)
print("list1的类型:",type(list1))
print(list1)
print(list(list1))
for i in enumerate(lang,1):
print(i)
运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
list1的类型: <class 'enumerate'>
<enumerate object at 0x000001E137D1F780>
[(1, 'java'), (2, 'go'), (3, 'c'), (4, 'vb'), (5, 'c++')]
(1, 'java')
(2, 'go')
(3, 'c')
(4, 'vb')
(5, 'c++')
enumerate() 函数可以快速实现对可迭代对象中的元素建立索引和编号。例如:
stu = ["刘刚","张静静","王芸","张云涛","刘贝贝"]
list1 = enumerate(stu,1)
for item in list1:
print(item)
运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
(1, '刘刚')
(2, '张静静')
(3, '王芸')
(4, '张云涛')
(5, '刘贝贝')
也可以在序列中直接使用 enumerate() 函数:
stu = ["刘刚","张静静","王芸","张云涛","刘贝贝"]
for item in enumerate(stu,1):
print(item)
运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
(1, '刘刚')
(2, '张静静')
(3, '王芸')
(4, '张云涛')
(5, '刘贝贝')
字符串可以使用 enumerate() 函数建立索引序号:
str = "张王李赵刘曹关"
for item in enumerate(str,1):
print(item)
运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
(1, '张')
(2, '王')
(3, '李')
(4, '赵')
(5, '刘')
(6, '曹')
(7, '关')
str = "张王李赵刘曹关"
name = dict(enumerate(str,1))
print(name)
运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
{1: '张', 2: '王', 3: '李', 4: '赵', 5: '刘', 6: '曹', 7: '关'}
str = ["马芸","马花疼","黄征","丁蕾","许志军","张三疯"]
name = dict(enumerate(str,1))
print(name)
运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
{1: '马芸', 2: '马花疼', 3: '黄征', 4: '丁蕾', 5: '许志军', 6: '张三疯'}
str = ["马芸","马花疼","黄征","丁蕾","许志军","张三疯"]
name = dict((item,i) for i,item in enumerate(str,1))
print(name)
运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
{'马芸': 1, '马花疼': 2, '黄征': 3, '丁蕾': 4, '许志军': 5, '张三疯': 6}
使用 enumerate() 函数可以为字典的键建立索引,生成由序号与字典的键组成的元组。例如:
dict = {"马芸":20,"马花疼":85,"黄征":76,"丁蕾":88,"许志军":102,"张三疯":56}
for item in enumerate(dict,1):
print(item)
for i,item in enumerate(dict,1):
print(i,":",item,end=" ")
运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
(1, '马芸')
(2, '马花疼')
(3, '黄征')
(4, '丁蕾')
(5, '许志军')
(6, '张三疯')
1 : 马芸 2 : 马花疼 3 : 黄征 4 : 丁蕾 5 : 许志军 6 : 张三疯