enumerate()函数名比较长,用来查看可迭代对象的索引及值,与循环搭配使用,可以代码更加简洁。
Python内置函数 enumerate()
enumerate()函数作用于序列或可迭代对象,返回一个枚举对象(enumerate object),包含序列及数据。与循环搭配使用可使代码更简洁。
1. 语法 enumerate(iterable, start=0)
iterable 可迭代对象,必选
start,设置初始值,可选,默认0
1.1 列表
In [1]:
list1 = ['甲', '乙', '丙', '丁']
In [2]:
list(enumerate(list1, start = 0))
Out[2]:
[(0, '甲'), (1, '乙'), (2, '丙'), (3, '丁')]
In [3]:
list(enumerate(list1))
Out[3]:
[(0, '甲'), (1, '乙'), (2, '丙'), (3, '丁')]
In [4]:
list(enumerate(list1, start = 2))
Out[4]:
[(2, '甲'), (3, '乙'), (4, '丙'), (5, '丁')]
1.2 元组
In [5]:
tuple1 = ('A', 'B', 'C', 'D')
In [6]:
enumerate(tuple1)
Out[6]:
In [7]:
list(enumerate(tuple1))
Out[7]:
[(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D')]
1.3 字符串
In [8]:
str1 = 'Python'
In [9]:
list(enumerate(str1, start = 1))
Out[9]:
[(1, 'P'), (2, 'y'), (3, 't'), (4, 'h'), (5, 'o'), (6, 'n')]
1.4 range()
In [10]:
list(enumerate(range(9), start = 1))
Out[10]:
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6), (8, 7), (9, 8)]
1.5 字典 返回字典的键
In [11]:
dic1 = {'A':'甲', 'B':'乙', 'C':'丙', 'D':'丁'}
In [12]:
list(enumerate(dic1, start = 1))
Out[12]:
[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D')]
2. 与for循环搭配使用
In [13]:
for i in enumerate(dic1):
print(i)
(0, 'A')
(1, 'B')
(2, 'C')
(3, 'D')
In [14]:
for a, b in enumerate(list1):
print('%r---%r' % (a, b))
0---'甲'
1---'乙'
2---'丙'
3---'丁'
In [15]:
for c, d in enumerate(tuple1):
print(c, tuple1[c])
0 A
1 B
2 C
3 D
In [16]:
for e in enumerate('Python',start = 1):
print(e)
(1, 'P')
(2, 'y')
(3, 't')
(4, 'h')
(5, 'o')
(6, 'n')
python enumerate