19-python-迭代器、生成器

一、递归于迭代

       迭代:下一组数据的由上一组数据next方法提供,只能往后走,不能往前走。

  在列表中,由方法a=l.__iter__()把使列表遵循迭代器协议,转换成可迭代对象  可以用a.next()方法取列表数据

  

二、用for循环,循环可迭代对象的原理

  

 1 # -*- coding:utf-8 -*-
 2 
 3 s=[1,2,3,4,5,6,7]
 4 iter_s=s.__iter__()
 5 while True:
 6     try:
 7         print(iter_s.__next__())
 8     except StopIteration:
 9         print("遍历结束")
10         break

三、生成器表达式    优势就是占用内存少,用一个给一个

  生成器本身就是可迭代对象   

  x=x.__inter__()  生成器

  x.__next__()

1 def test():
2     yield 1
3     yield 2  # yield 相当于return,但是可以返回多次   函数类型的生成器
4 
5 g=test()
6 print(g)
7 print(g.__next__())

补充点:三元表达式

1 name="zf"
2 a="good" if name=="zf" else "SB"
3 print(a)

列表解析

 
 1 # -*- coding:utf-8 -*-
 2 
 3 egg_list = []
 4 for i in range(1, 11):
 5     egg_list.append("egg%s" % i)
 6 print(egg_list)
 7 
 8 l = ["egg%s" % i for i in range(1, 11)]    #该程序占用内存量大
 9 print(l)
10 
11 ll = ["egg%s" % i for i in range(1, 11) if i % 2 == 0]  # 三元表达式  三元表示式只能小于等于3元
12 print(ll)

以下程序就是生成器表达式

1 laomuji = ("egg%s" % i for i in range(1, 11))    #  这个就是生成器表达式   使用生成器可以减少内存使用
2 print(laomuji)
3 print(laomuji.__next__())

例子:文件中的各省人口普查的人口数据,统计总人口,并求组各省的占比

 1 # -*- coding:utf-8 -*-
 2 
 3 def get_population():
 4     with open("人口普查.txt","r",encoding="utf-8") as f:
 5         for i in f:
 6             yield i
 7 
 8 g=get_population()  # 数据循环完毕后,就丢失。
 9 
10 all_population=sum(eval(i)["population"] for i in g)
11 print(all_population)
12 g1=get_population()
13 for i in g1:
14     percent=eval(i)["population"]/all_population*100
15     print("%.4f %%"%percent)

迭代对象调用next方法

 1 def get_population():
 2     with open("人口普查.txt", "r", encoding="utf-8") as f:
 3         for i in f:
 4             yield i
 5 
 6 
 7 g = get_population() 
 8 print(g.__next__())
 9 print(next(g))
10 print(g.send(None))

send方法

 1 # -*- coding:utf-8 -*-
 2 def test():
 3     first=yield 1  #接受send传过来的值
 4     print(first)
 5     yield 2
 6     yield 3
 7 
 8 t=test()
 9 res=t.__next__()
10 print(res)
11 t.send(4)  

生产消费模型

 1 # -*- coding:utf-8 -*-
 2 
 3 import time
 4 def consumer(name):
 5     print("我是%s,我准备吃包子了"%name)
 6     while True:
 7         baozi=yield
 8         time.sleep(1)
 9         print("%s,把%s吃掉了"%(name,baozi))
10 
11 def producer():
12     c1=consumer("zf")
13     c1.__next__()
14     for i in range(1,11):
15         time.sleep(1)
16         c1.send("包子%s"%i)
17 
18 producer()
原文地址:https://www.cnblogs.com/zhfang/p/8870528.html