What about?
while BoolIter(N, default=True, falseIndex=N-1): print 'some thing'
or in an uglier way:
for _ in BoolIter(N): print 'doing somthing'
or if you want to intercept the last time:
for lastIteration in BoolIter(N, default=False, trueIndex=N-1): if not lastIteration: print 'still going' else: print 'last time'
Where:
class BoolIter(object): def __init__(self, n, default=False, falseIndex=None, trueIndex=None, falseIndexes=[], trueIndexes=[], emitObject=False): self.n = n self.i = None self._default = default self._falseIndexes=set(falseIndexes) self._trueIndexes=set(trueIndexes) if falseIndex is not None: self._falseIndexes.add(falseIndex) if trueIndex is not None: self._trueIndexes.add(trueIndex) self._emitObject = emitObject def __iter__(self): return self def next(self): if self.i is None: self.i = 0 else: self.i += 1 if self.i == self.n: raise StopIteration if self._emitObject: return self else: return self.__nonzero__() def __nonzero__(self): i = self.i if i in self._trueIndexes: return True if i in self._falseIndexes: return False return self._default def __bool__(self): return self.__nonzero__()
DangerMouse Jun 09 '15 at 11:47 2015-06-09 11:47
source share