Python標準庫-enumerate用法
阿新 • • 發佈:2017-11-28
tin def .py value ref 3.6 ini 數字 cut .
enumerate 枚舉
enumerate
(iterable, start=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用法