首页 > 编程语言 > 详细

Python标准库-enumerate用法

时间:2017-11-27 23:14:27      阅读:310      评论:0      收藏:0      [点我收藏+]

enumerate 枚举

enumerate(iterablestart=0)

Return an enumerate object. iterable 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 iterable.

将一个可支持迭代的对象,转化为枚举, 所以列表,序列,或者其他可迭代的对象即可以;枚举会返回一个包含数字和迭代器中的值的元组;最终返回一个可枚举对象;

典型用法:

 

seasons = [‘Spring‘, ‘Summer‘, ‘Fall‘, ‘Winter‘]
list(enumerate(seasons))
[(0, ‘Spring‘), (1, ‘Summer‘), (2, ‘Fall‘), (3, ‘Winter‘)]
 

简单实现:

def enumerate(sequence, start=0):
    n = start
    for x in sequence:
        yield n, x
        n += 1

  

 

Python标准库-enumerate用法

原文:http://www.cnblogs.com/skadieye/p/7906259.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!