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

1.迭代器

迭代器是一个能够记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到全部的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
使用时首先判断是不是能够迭代,用isinstance()方法判断或者能够for循环的遍历的对象是可迭代对象,能够被next()函数调用,并不断返回下一个值得对象。python

判断是否能够迭代算法

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')

输出结果:bash

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=" ")

结果:app

true
3 12 22 33

字符串,列表或元组对象均可用于建立迭代器:函数

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

输出结果:ui

3
12

使用常规for语句进行遍历:lua

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

输出结果:spa

3 12 22 33

2.生成器

生成器自动建立了_iter_()和_next_()内置方法仅仅保存了一套生成数值的算法,调用时,才去计算而后返回一个值。生成器必定是迭代器,而迭代器不必定是生成器,一边循环一边计算的机制称为生成器,含有yield语句的函数,能够减小内存空间。code

在 Python 中,使用了 yield 的函数被称为生成器(generator)。
跟普通函数不一样的是,生成器是一个返回迭代器的函数,只能用于迭代操做,更简单点理解生成器就是一个迭代器。
在调用生成器运行的过程当中,每次遇到 yield 时函数会暂停并保存当前全部的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。
调用一个生成器函数,返回的是一个迭代器对象。对象

#!/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
相关文章
相关标签/搜索