python reverse iterator and generator ways
Post:2018-07-12 23:30:50
Visit:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| \ \ \ \ \
class ReverseIterator(): def \_\_init\_\_(self, str_data): self.str\_data = str\_data self.index = len(str_data) def \_\_iter\_\_(self): return self def \_\_next\_\_(self): if self.index == 0: raise StopIteration else: self.index = self.index - 1 return self.str_data\[self.index\] def reservse_genertor(data): for index in range(len(data)-1, -1, -1): yield data\[index\]
def main(): example_string = 'simon.xie' ri = ReverseIterator(example_string) new\_str\_list = \[\] for char in ri: new\_str\_list.append(char) print(''.join(new\_str\_list))
other\_str\_list = \[\] rg = reservse\_genertor(example\_string) for char in rg: other\_str\_list.append(char) print(''.join(other\_str\_list))
if \_\_name\_\_ == "\_\_main\_\_": main()
|
感谢鼓励