欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

函数-生成器、迭代器

程序员文章站 2024-01-02 10:08:10
1 import time 2 3 def tourist(name): 4 print("%s 开始吃包子" % name) 5 while True: 6 baozi = yield #生成器函数(generator) 7 print("%s吃了第%s个" % (name, baozi)) 8 ......
#-----列表生成器-----

1 a = [x*2 for x in range(10)]
2 print(a,type(a)) #[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] <class 'list'>
3 
4 def f(n):
5     return n**3
6 
7 a = [f(x) for x in range(10)]
8 print(a,type(a)) #[0, 1, 8, 27, 64, 125, 216, 343, 512, 729] <class 'list'>

 

#-----简单赋值方式

1 t = (12,45)
2 a,b = t
3 print(a)#12
4 print(b)#45

 

#----生成器(生成器就是可迭代对象)-----

 1 s = (x*2 for x in range(10))
 2 for i in s:
 3     print(i,end=" ") # 0 2 4 6 8 10 12 14 16 18
 4 
 5 #可迭代对象 :内部有iter 方法
 6 a = (1,2,3,5)
 7 a.__iter__()
 8 b = [2,3,4,5]
 9 b.__iter__()
10 c = {"a":"d","g":"r"}
11 c.__iter__()
12 e = set(a)
13 print(e,type(e))
14 e.__iter__()

 

#-----yield关键字生成斐波那契数列

 1 def fib(max):
 2     n,before,after = 0,0,1
 3     while n < max:
 4         yield after
 5         before,after = after,before+after
 6         n += 1
 7 
 8 g = fib(6)
 9 for i in g:
10     print(i)

 

#-----yield 使用

 1 def bar():
 2     print("ok1")
 3     str1 = yield 1
 4     print(str1)
 5 
 6     print("ok2")
 7     str2 = yield 2
 8     print(str2)
 9 b = bar()
10 next(b)
11 ret = b.send("ee")
12 print(ret)

 

#-----还可通过yield实现在单线程的情况下实现并发运算的效果

 1 import time
 2 
 3 def tourist(name):
 4     print("%s 开始吃包子" % name)
 5     while true:
 6         baozi = yield  #生成器函数(generator)
 7         print("%s吃了第%s个" % (name, baozi))
 8 
 9 def cook(name):
10     c1  = tourist("a")
11     c2 = tourist("b")
12     c1.__next__()
13     c2.__next__()
14     print("%s开始做包子了" % name)
15     for i in range(1,10):
16         time.sleep(0.2)
17         c1.send(i)
18         c2.send(i)
19 cook("dream")

 

#-----迭代器-----

1、有iter方法
2、有next方法
1 a = ["dream","rise","happy"]
2 d = iter(a) #<list_iterator object at 0x000001e01bfada90>
3 print(d)
4 print(a.__iter__())#<list_iterator object at 0x00000258f8392668>
					

上一篇:

下一篇: