2016年6月28日 星期二

Python_enumerate()

enumerate(iterable, start=0)

https://docs.python.org/3.5/library/functions.html#enumerate

傳以 iterable 與連續整數配對的 enumerate 物件, 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')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Equivalent to:
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

同理,呼叫串列中的元素,一般都是使用下列方式:
In[4]: seasons = ['Spring', 'Summer', 'Fall', 'Winter']
In[5]: for i in range(len(seasons)):
...     print(seasons[i])
...  
Out:
Spring
Summer
Fall
Winter

可以改用enumerate(),如:
In[6]: seasons = ['Spring', 'Summer', 'Fall', 'Winter']
In[7]: for index, element in enumerate(seasons):
...     print(index,element)
...  
Out:
0 Spring
1 Summer
2 Fall
3 Winter

串列list中找出重複元素的位置(index)

藉由enumerate()能同時將index 及 element同時取出的功能,可以用來取出串列中重複元素的index

範例:
In[21]: num = [1,2,3,2,1,11,12,13,1,2,3,4,5,2,1,1]
In[22]: for index,element in enumerate(num):
...     if element == 1:
...         print(index)
...      
Out:
0
4
8
14
15

沒有留言:

張貼留言