python - Creating a function which reverses iterator -
i'm doing in attempt better understand iter()
, next()
methods better.
so understand can done using built-ins:
>>>animal = 'cat' >>>print(list(reversed(animal))) ['t','a','c']
but can done creating class iterable:
class reverselist(): def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise stopiteration self.index =self.index -1 return self.data[self.index] def intolist(self): self.test = [i in self] return self.test rev = reverselist('cat') print(rev.intolist()) ['t','a','c']
however, i'm having trouble doing same thing using functions instead of going ooo route.
is there way functions using iter()
, next()
methods without having resort comprehensions , loops?
you can generator function:
def reverse_list(seq): index in range(len(seq)-1, -1, -1): yield seq[index]
calling function produce "generator object" supports iter()
, next()
.
>>> rev = reverse_list('cat') >>> rev <generator object reverse_list @ 0x10a93ebe0> >>> next(rev) 't'
Comments
Post a Comment