title: python迭代器
data: 2018-4-7
categories:
- python
tags: - python
容器(container)、可迭代对象(iterable)、迭代器(iterator)、生成器(generator)、
列表(list)、集合(set)、字典推导式(dict comprehension)
class Fibs:
def __init__(self):
self.a = 0
self.b = 1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
return self.a
fib = Fibs()
for i in fib:
if i < 10:
print(i, end=" ")
else:
break
结果:
1 1 2 3 5 8
class squares:
def __init__(self, start, stop):
self.flag = start - 1
self.value = self.flag
self.stop = stop
def __iter__(self):
self.value = self.flag
return self
def __next__(self):
if self.value == self.stop:
raise StopIteration
self.value += 1
return self.value
a = squares(1, 5)
b = squares(1, 5)
s = 0
while s <= 41:
for i in a:
s = s + i
print(s, end=" ")
结果:
1 3 6 10 15 16 18 21 25 30 31 33 36 40 45
class test():
def __init__(self,data=1):
self.data = data
def __iter__(self):
return self
def __next__(self):
if self.data > 5:
raise StopIteration
else:
self.data+=1
return self.data
for item in test(3):
print(item, end=" ")
结果:
4 5 6