# Python中迭代器和生成器的区别与联系

#### 1.迭代器

from collections import Iterable

str = 'abc'
if isinstance(str,Iterable):
print('true')
arr = [1,2,3]
if isinstance(arr,Iterable):
print('true')
tup = (1,'q',4)
if isinstance(tup,Iterable):
print('true')
dict = {'a':'1'}
if isinstance(dict,Iterable):
print('true')
a = 123
if isinstance(a,Iterable):
print('true')
else:
print('false')

true
true
true
true
false
arr = [3,12,22,33]
if isinstance (arr,(str,tuple,list)):
print('true')
else:
print('error')
it = iter(arr)
for i in it:
print(i,end=" ")

true
3 12 22 33 

list = [3,12,22,33]
it = iter(list)   #创建一个迭代器对象
print(next(it))   #输出迭代器的下一个对象
print(next(it))

3
12

list = [3,12,22,33]
it = iter(list)
for i in it:
print(i,end=" ")

3 12 22 33 

#### 2.生成器

#!/usr/bin/python3

import 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