协程函数、递归调用

1、消费者生产者模型初级

2、获取指定目录下子目录与文件

3、递归调用

--消费者生产者模型初级

def eater(name):
    print('%s start to eat' %name )
    while True:
        food = yield
        print('%s eat %s' %(name,food))
        
        
alex_g = eater('alex')#先获得生成器
next(alex_g)#触发函数使函数暂停到函数的yield
alex_g.send('骨头')#给yield发送个值,使yield赋值给food,然后执行函数


--#改进使其能交互,并使生产者获取清单保存消费项目

def eater(name):
    food_list =[]
    print('%s start to eat' %name )
    while True:
        food = yield food_list
        food_list.append(food)
        print('%s eat %s' %(name,food))

def producter():
    alex_g = eater('alex')  # 先获得生成器
    next(alex_g)  # 触发函数使函数暂停到函数的yield
    while True:
        inp = input('>>>')
        print(alex_g.send(inp))#给yield发送个值,使yield赋值给food,然后执行函数
producter()

--改进使初始化咋装饰器中进行

def init(func):
    def wapper(*args,**kwargs):
        alex_g = func(*args,**kwargs)  # 先获得生成器
        next(alex_g)  # 触发函数使函数暂停到函数的yield
        return alex_g
    return wapper

@init
def eater(name):
    food_list =[]
    print('%s start to eat' %name )
    while True:
        food = yield food_list
        food_list.append(food)
        print('%s eat %s' %(name,food))

def producter():
    g = eater('alex')#调用eater函数--》装饰器执行func(alex)获得生成器--》使暂停到eater的yield--》执行装饰器中初始化--》将生成器返回给g
    while True:
        inp = input('>>>')
        print(g.send(inp))#给yield发送个值,使yield赋值给food,然后执行函数
producter()

--获取指定目录下子目录与文件

import os
t = os.walk(r'C:UsersliguangxuPycharmProjectsuntitled2')#这里会获得一个迭代器
print(next(t))
#获得该目录下的子目录与文件,元组的第一个元素为指定目录,第二个元素为目录下的文件夹,第三个元素为指定目录的文件
#('C:\Users\liguangxu\PycharmProjects\untitled2', ['.idea', '111', 'day3', 'day4', 'day5'], [])
print(next(t))
#第一个元素为第一个指定目录下的文件夹,第二个元素为第一个指定目录下的文件夹下的文件夹,第三个为指定目录下的第一个目录下的文件
#('C:\Users\liguangxu\PycharmProjects\untitled2\.idea', [], ['misc.xml', 'modules.xml', 'untitled2.iml', 'workspace.xml'])
#想要获取指定目录下的所有文件的绝对路径的方法
import os
t = os.walk(r'C:UsersliguangxuPycharmProjectsuntitled2')
for pardir,_,files in t:#将第一个元素(目录)和第三个元素(目录下的文件)拿到做拼接
for file in files:
abspath = r'%s\%s'%(pardir,file)
print(abspath)

--递归调用
#递归调用:在调用一个函数的过程中,直接或者间接的调用了函数本身
#效率低,必须有一个明确的结束条件,没进入更深一层递归时,问题规模相比上一次递归减少
#查看递归层级 sys.getrecursionlimit() 修改递归层级 sys.getrecursionlimit()

def  age(n):
    if n == 1:
        return 18
    return age(n-1)+2
print(age(5))

l = [1,2,[3,4,5,6,[7,8,9,[10,11,12]]]]
def li(l):
    for item in l:
        if type(item) is list:
            li(item)
        else:
            print(item)
    
原文地址:https://www.cnblogs.com/kunixiwa/p/7267988.html