标签:python
本函数是把可迭代对象转换为枚举对象。iterable是可迭代参数,比如像列表、数组、字典等对象;start是枚举的起始值,默认是从0开始。这个函数实现原理是这样,从迭代对象的方法__next__()取得一项值,然后就对参数start开始计数,每取一项增加1,生成一个元组返回。
本函数实现原理,大体上可以用下面的代码来表示:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
下面就来看看例子:
#enumerate() l = [‘a‘, ‘b‘, ‘c‘] print(list(enumerate(l))) t = (‘快乐‘, ‘高兴‘, ‘开心‘) print(list(enumerate(t))) d = {‘深圳‘:1, ‘广州‘:2, ‘珠海‘:3} print(list(enumerate(d, 2))) s = ‘深圳是一个高科技的超级城市,人口拥有1800万人‘ print(list(enumerate(s, 1)))
结果输出如下:
[(0, ‘a‘), (1, ‘b‘), (2, ‘c‘)]
[(0, ‘快乐‘), (1, ‘高兴‘), (2, ‘开心‘)]
[(2, ‘深圳‘), (3, ‘珠海‘), (4, ‘广州‘)]
[(1, ‘深‘), (2, ‘圳‘), (3, ‘是‘), (4, ‘一‘), (5, ‘个‘), (6, ‘高‘), (7, ‘科‘), (8, ‘技‘), (9, ‘的‘), (10, ‘超‘), (11, ‘级‘), (12, ‘城‘), (13, ‘市‘), (14, ‘,‘), (15, ‘人‘), (16, ‘口‘), (17, ‘拥‘), (18, ‘有‘), (19, ‘1‘), (20, ‘8‘), (21, ‘0‘), (22, ‘0‘), (23, ‘万‘), (24, ‘人‘)]
蔡军生 QQ:9073204 深圳
Python标准库:内置函数enumerate(iterable, start=0)
标签:python
原文地址:http://blog.csdn.net/caimouse/article/details/41408527