当前位置:首页 > Python教程 > python技巧

python之enumerate函数使用

enumerate函数可以同时获取索引,以及值,用next()方法调用。


例1:

>>> s = ‘hello word‘       #########s为可迭代对象

>>> h = enumerate(s)

>>> h

<enumerate object at 0x7f1d66848a50>

>>> h.next()

(0, ‘h‘)

>>> h.next()

(1, ‘e‘)

>>> h.next()

(2, ‘l‘)

>>> h.next()

(3, ‘l‘)

>>> h.next()

(4, ‘o‘)

>>> h.next()

(5, ‘ ‘)

>>> h.next()

(6, ‘w‘)

>>> h.next()

(7, ‘o‘)

>>> h.next()

(8, ‘r‘)

>>> h.next()

(9, ‘d‘)

例2:

>>> for i,j in enumerate(s):    ###########用于for循环

...     i,j

... 

(0, ‘h‘)

(1, ‘e‘)

(2, ‘l‘)

(3, ‘l‘)

(4, ‘o‘)

(5, ‘ ‘)

(6, ‘w‘)

(7, ‘o‘)

(8, ‘r‘)

(9, ‘d‘)


原文:http://weilantiankong.blog.51cto.com/9469693/1754552


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!