Python生成器

  生成器是Python新引入的概念,生成器可以帮助我们写出非常优雅的代码

1. 生成器

  使用yield语句,每次产生一个值,函数就会被冻结 

def fun(li):
    for i in li:
        #print (i)
        yield i

li = [1,2,3,4,5]
for i in fun(li):
    print (i)

2.列表推导式

  可以用来创建list

  例:生成[1*1, 2*2, 3*3, 4*4, 5*5]的列表,即[1,4,9,16,25]

#方法1
def fun1():
    l = []
    for i in range(1,6):
        l.append(i * i)
    return l

print (fun1())

#方法2
def fun2():
    return (i*i for i in range(1,6))

ll = list(fun2())
print (ll)

#方法3
def fun3():
    for i in range(1,6):
        yield i*i
for i in fun3():
    print (i)
输出:
>>>> [1,4,9,16,25] >>>> [1,4,9,16,25]
>>>> 1
>>>> 4
>>>> 9
>>>> 16
>>>> 25
特别注意在斐波那契数列例子中a,b=b,a+b语法

3. yield实现协程任务器调度

#coding = utf-8

'''
    yield实现协程任务调度
'''
from collections import deque

class TaskScheduler:
    def __init__(self):
        self.taskqueue = deque()

    def new_task(self, task):
        self.taskqueue.append(task)

    def run(self):
        while self.taskqueue:
            task = self.taskqueue.popleft()
            try:
  
                next(task)
                self.taskqueue.append(task)
            except Exception:
                print ("run exception")

def task1(n):
    while n > 0:
        print ("say hello: %d" %(n))
        yield n
        n -=1
    print ("task1 say goodble")

def task2(n):
    x= 0
    while x < n:
        print ("say hi:%d" %(x))
        yield x
        x += 1

    print ("task2 say goodbye")

taskschequler = TaskScheduler()
taskschequler.new_task(task1(4))
taskschequler.new_task(task2(4))
taskschequler.run()
    
原文地址:https://www.cnblogs.com/xiaobingqianrui/p/8295494.html