[Tutor] updating step size while in loop
Wayne Werner
wayne at waynewerner.com
Tue Jul 10 06:08:59 CEST 2012
While you can't do it with a straight generator, you can create your own:
class MyIter:
def __init__(self, start, stop, step=1):
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
self.cur = self.start
while self.cur < self.stop:
yield self.cur
self.cur += 1
And then you could do the following:
In [36]: i = MyIter(1, 10)
In [37]: for x in i:
....: if x % 2:
....: i.cur += 1
....: print(x)
....:
1
3
5
7
9
-HTH,
Wayne
On Tue, 10 Jul 2012, Hugo Arts wrote:
> On Mon, Jul 9, 2012 at 11:59 PM, Abhishek Pratap <abhishek.vit at gmail.com>
> wrote:
> hey guys
>
> I want to know whether it is possible for dynamically update the
> step
> size in xrange or someother slick way.
>
> Here is what I am trying to do, if during a loop I find the x in
> list
> I want to skip next #n iterations.
>
>
> for x in xrange(start,stop,step):
> if x in list:
> step = 14
> else:
> step = 1
>
>
>
> Thanks!
> -Abhi
>
>
> It is not possible with a range object. You'll have to make a while loop and
> keep track of the step yourself.
>
> Hugo
>
>
More information about the Tutor
mailing list