迭代器和生成器复习

Posted bigdata_devops

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了迭代器和生成器复习相关的知识,希望对你有一定的参考价值。

初步铺垫:

for i in [1,2,3,4]:
pass
 
l = [1,2,3,4]
 
l2 = iter(l)
print(l2.__next__())
print(l2.__next__)
 
print(range(100)) #range(100) 就是一个生成器,为了节省内存,值不会直接输出
print(range(0,100))

#两种range取值方法:

print(list(range(100))) #通过列表
for i in range(100): #通过for循环
    print(i)
print(list(range(1,100,2))) #步长
生成器变形计划:

生成器变形计划:

一级变形:

def a():
    a = 0
    while True:
        # return a
        yield a
        a = a+1
 
print(a().__next__())
print(a().__next__())  #全是0,每次重新执行那个函数,这个函数就会重新执行

二级变形:

def a():
    a = 0
    while True:
        # return a
        yield a
        a = a+1
 
l = a()
print(l)
print(l.__next__()) #next可以递归的取值,是因为l始终指得是一个函数
print(l.__next__())
print(l.__next__())

三级变形:

def test2():
    # for i in range(1,6):
    #     yield i #冻结
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
 
l=test2()
print(l.__next__())
print(l.__next__())
print(l.__next__())

四级变形:(模拟range功能)

def range2():
    start = 0
    while start<10:
        yield start*4
        start += 1
 
for i in range2():
    print(i)

五级变形:

def range2():
    start = 0
    l = []
    while start<100:
        l.append(start*4)
        start += 1
    return l
print(range2())

六级变形:

def range3():
    start = 0
    while True:
        yield start*4
        start += 1
 
# print(range3())
for i in range3():
    print(i)

练习之变形计划

练习一:

"1+1+2+3+5..." #斐波那契数列

#初步:
def test():
    a,b = 1,1
    while a<10:
        c = a + b
        yield c
        a = b
        b = c
print(test())
l = test()
print(l.__next__())
print(l.__next__())
for i in l:
    print(i)
 
 
#终极:
def test4():
    a = 1
    yield a
    b = 1
    yield b
    while True:
        c = a+b
        yield c
        a = b
        b = c
 
l = test4()
print(l.__next__())
print(l.__next__())
print(l.__next__())
print(l.__next__())
print(l.__next__())
# for i in l:
#     print(i)

练习二:

母鸡下蛋例子

def test3():
    i = 0
    while i < 10:
        yield 母鸡下了个蛋,这是第%s个蛋%(i+1)
        i += 1
 
l = test3()
 
print(l.__next__())
print(l.__next__())
print(l.__next__())
for i in l:
    print(i)

 

以上是关于迭代器和生成器复习的主要内容,如果未能解决你的问题,请参考以下文章

迭代器和生成器复习

Python之迭代器和生成器

Python基础复习函数篇

迭代器和生成器

python函数:迭代器和生成器

python函数:迭代器和生成器