python中enumerate用法

简单的来说下:list = ['a', 'b', 'c']
要求打印出每一个元素的索引和改元素,一种笨拙的方法:
list = ['a', 'b', 'c']for i in range(0, len(list)):print i, list[i]0 a1 b2 c

现在来用enumerate来解决这个问题:

for i, j in enumerate(list):... print i, j...0 a1 b2 c>>>

好了,enumerate的官方解释为:
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence

详见:https://docs.python.org/2/library/functions.html#enumerate

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容