python3 迭代器,生成器

一 、什么是迭代
1、 重复
2、下次重复一定是基于上一次的结果而来
    while True:
        cmd=input(':')
        print(cmd)


    l=[1,2,3,4]
    count=0
    while count < len(l):
        print(l[count])
        count+=1

二、 可迭代对象:obj.__iter__

三 、迭代器:iter1=obj.__iter__()
1 iter1.__next__
2 iter1.__iter__

iter1.__next__()
iter1.__next__()
iter1.__next__()

迭代器:
优点:
1 不依赖索引
2 惰性计算,节省内存

缺点:
1 不如按照索引的取值方便
2 一次性,只能往后取,不能回退
    l=[1,2,3]
    for i in l: # obj=l.__iter__()
        print(i)

迭代器的应用:
1、提供了一种不依赖索引的统一的迭代方法
2、 惰性计算,比如取文件的每一行

list = [1,2,3,4,5]
i = iter(list) #迭代器函数
print(i.__next__())
print(i.__next__())
print(i.__next__())
print(i.__next__())
print(i.__next__())


i = list.__iter__() #迭代器对象
i.__next__()

s1='hello'
s1.__iter__()
l=[1,2,3]
l.__iter__()
t=(1,2,3)
t.__iter__()
set1={1,2,3}
set1.__iter__()
d={'a':1,'b':2,'c':3}
d.__iter__()


f=open('db.txt',encoding='utf-8')
print(f.__next__())

生成器函数

生成器函数:函数体内包含有yield关键字,该函数执行的结果是生成器

def foo():
    print('first------>')
    yield 1
    print('second----->')
    yield 2
    print('third----->')
    yield 3
    print('fouth----->')

g=foo()

print(g)
from collections import Iterator
print(isinstance(g,Iterator))

生成器就是迭代器

print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())


for i in g:   #obj=g.__iter__() #obj.__next__()
print(i)


'''
yield的功能:
1.与return类似,都可以返回值,但不一样的地方在于yield返回多次值,而return只能返回一次值
2.为函数封装好了__iter__和__next__方法,把函数的执行结果做成了迭代器
3.遵循迭代器的取值方式obj.__next__(),触发的函数的执行,函数暂停与再继续的状态都是由yield保存的
'''
def countdown(n):
    print('starting countdown')

    while n > 0:
        yield n
        n-=1
    print('stop countdown')
g=countdown(5)
print(g)
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())

for i in g:
    print(i)

 

生成器函数补充:迭代器的特性,不能循环取值
def countdown(n):
    while n > 0:
        yield n
        n-=1

g=countdown(5)
print(g.__next__())
print(g.__next__())

print('='*20)
for i in g:
    print(i)

print('*'*20)
for i in g:
    print(i)



for i in countdown(5):
    print(i)
print('*'*20)
for i in countdown(5):
    print(i)
print('*'*20)
for i in countdown(5):
    print(i)


print(countdown(5).__next__())    #g才是迭代器
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())
print(countdown(5).__next__())



print(countdown(5),countdown(5),countdown(5))

  

posted on 2017-06-19 20:10  lucaq  阅读(268)  评论(0编辑  收藏  举报

导航