2016-05-15 47 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)元组,您可以指定使用的元组分配两个独立的变量。