Nasıl olur?
while BoolIter(N, default=True, falseIndex=N-1):
print 'some thing'
veya daha çirkin bir şekilde:
for _ in BoolIter(N):
print 'doing somthing'
veya son seferde:
for lastIteration in BoolIter(N, default=False, trueIndex=N-1):
if not lastIteration:
print 'still going'
else:
print 'last time'
nerede:
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__()