搞懂Python函数的定义与调用
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
字符串,列表或元组对象都可用于创建迭代器:
list = ["dog","cat","cow","lion","wolf"]
# 创建迭代器对象
it = iter(list)
for x in it:
print (x, end=" ")
dog cat cow lion wolf
import sys # 引入 sys 模块
list = ["dog","cat","cow","lion","wolf"]
# 创建迭代器对象
it = iter(list)
while True:
try:
print (next(it))
except StopIteration:
sys.exit()
dog
cat
cow
lion
wolf
class NumberCount:
def __iter__(self):
self.number = 1
return self
def __next__(self):
x = self.number
self.number += 1
return x
y = NumberCount()
z = iter(y)
print(next(z))
print(next(z))
print(next(z))
1
2
3
class NumberCount:
def __iter__(self):
self.number = 1
return self
def __next__(self):
if self.number <= 5:
x = self.number
self.number += 1
return x
else:
raise StopIteration
y = NumberCount()
z = iter(y)
for x in z:
print(x)
1
2
3
4
5
import sys # 引入 sys 模块
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
0 1 1 2 3 5 8 13 21 34 55