2016-05-15 49 views
0

所以我有一個字符串source,在我與循環迭代器:如何查看我的迭代器在哪個索引處?

iterator = iter(source) 
for char in iterator: 
    do stuff 

不過,現在說我有一張支票在do stuff,在那裏我迭代器的值進行比較,以「H」。然後,我想以某種方式查看「h」後面是「ello」,並將之後的前十個字符添加到列表中。
對於這個我自己的想法是找出哪些指標與迭代器的當前位置對應,這樣我就可以說:

indIt = index(char) 
if source[indIt + 1: indIt + 6] == "ello ": 
    someList.append(source[indIt + 7:indIt + 16]) 
    indIt += 17 
    char = indIt #which may also be fun to know how it can be done, if 

這意味着,對於給定的輸入hello Sandra, oh and hello Oscar, i welcome you both!someList將包含[」桑德拉,哦,「奧斯卡,iw」]。

那麼,我可以在某種程度上找出迭代器的當前位置對應於哪個索引?

+7

使用'enumerate'。 – miradulo

+0

沒有這樣的功能。 – ppperry

+0

@ppperry:['enumerate()'](https://docs.python.org/2.3/whatsnew/section-enumerate.html)有什麼問題? – zondo

回答

6

迭代器不公開索引,因爲不一定要有一個序列

使用enumerate()函數添加一個到你的迭代:

for index, char in enumerate(iterator): 

現在迭代產生(index, value)元組,您可以指定使用的元組分配兩個獨立的變量。