class SimpleCounter(object):
def __init__(self, start, end):
self.start = start
self.current = self.start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1
class SimpleCounter1(object):
def __init__(self, start, end):
self.start = start
self.current = self.start
self.end = end
def __iter__(self):
return SimpleCounter(self.start, self.end)
def __next__(self):
if self.current > self.end:
self.current = self.start
raise StopIteration
else:
self.current += 1
return self.current - 1
simple_counter = SimpleCounter(1, 4)
print('first traversal simple_counter:')
for x in simple_counter:
print(x)
print('second traversal simple_counter:')
for x in simple_counter:
print(x)
simple_counter1 = SimpleCounter1(1, 4)
print('traversal simple_counter1...')
for x in simple_counter1:
print(x)
a = [0, 1, 2, 3, 4]
b = (x ** 2 for x in a)
print('traverse the iterator created by one generator for the first time:')
for x in b:
print(x);
print('traverse the iterator created by one generator for the second time:')
for x in b:
print(x);
注:
-python玩转数据科学之准备数据(使用到generator)