Python裏的enumerate

剛剛看了一下Python裏面的enumerate的部分, enumerate每次回返回一個tuple:(index, value)

例子很簡單:

for i, v in enumerate(['tic', 'tac', 'toe']):
    print i,v

在enumerate裏面我們可以放置一個iterable的對象,這樣的對象可以是a sequence, an iterator, or some other object which supports iteration。在Python doc 裏面看到這樣的解釋之後我便嘗試自己實現一個iterable的對象。實現如下:

class Enumerable:
    def __init__(self):
        self.value = 1
    def __iter__(self):
        return self
    def next(self):
        if (self.value > 10):
            raise StopIteration
        else:
            self.value += 1
            return self.value

enum = Enumerable()
for i, v in enumerate(enum):
    print i, v

只需要實現__iter__和next接口就可以了

enumerate( iterable)
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 zero) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), .... New in version 2.3.


A new built-in function, enumerate(), will make certain loops a bit clearer. enumerate(thing), where thing is either an iterator or a sequence, returns a iterator that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth.


A common idiom to change every element of a list looks like this:

for i in range(len(L)):
    item = L[i]
    # ... compute some result based on item ...
    L[i] = result

This can be rewritten using enumerate() as:

for i, item in enumerate(L):
    # ... compute some result based on item ...
    L[i] = result


轉自:http://taoyh163.blog.163.com/blog/static/195803562008196235218/



發佈了74 篇原創文章 · 獲贊 26 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章