Python递归函数中使用迭代器 Python编程怎样在递归函数中使用迭代器

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python递归函数中使用迭代器 Python编程怎样在递归函数中使用迭代器

frank_haha   2021-09-28 我要评论
想了解Python编程怎样在递归函数中使用迭代器的相关内容吗,frank_haha在本文为您仔细讲解Python递归函数中使用迭代器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python编程,Python递归函数迭代器使用,Python迭代器,下面大家一起来学习吧。

首先,想要实现的功能是递归遍历文件夹,遇到满足条件的文件时,用yield返回该文件的位置。

如果不用递归器,可以这样实现:

path_list = []
def get_one_cage(root: str, cook_folder_name: str):
    for item in os.listdir(root).copy():
        item_path = os.path.join(root, item)
        if item == cook_folder_name:
            path_list.append(item_path)
            return
        elif os.path.isdir(item_path):
            get_one_cage(item_path, cook_folder_name)

即,深度优先遍历,满足要求时,将item_path补充到列表里,之后返回上一层。
这里有一个问题,需要有一个列表,把所有满足条件的地址全存起来,占内存。

使用迭代器可以用一个,遍历出来一个,省内存

替换为迭代器,最先想到的是,把 return 换成 yield,使用for循环调用迭代器函数

def get_one_cage(root: str, cook_folder_name: str):
    for item in os.listdir(root).copy():
        item_path = os.path.join(root, item)
        if item == cook_folder_name:
            yield item_path
        elif os.path.isdir(item_path):
            get_one_cage(item_path, cook_folder_name)

但是这样的程序跑到内嵌函数时,进不去,我百思不得其解

现在看,应该是因为迭代器函数不是一个函数,不是一个命令语句,它只是一个对象。

简单说就是,python程序一般遵循:动词+名词的结构,或者动词,比如:

a = 1

这句话实际上是把1赋值给了a,是有动词的。
迭代器只是一个名词,必须用for语句调用或者next()方法调用才会执行,或者是print,yield,return等等,反正得加个动词,不能孤零零一个名词。
而且上述代码还有一个漏洞。在第一段代码中,我们用一个全局变量存放遍历结果。在第二段代码里,我们本意是把结果yield到for循环调用的地方,但事实是,程序已经套了好几层了,每次yiled只能返回一层。如下图所示:

在这里插入图片描述

综上两点作出如下修改:

def get_one_cage(root: str, cook_folder_name: str):
    for item in os.listdir(root).copy():
        item_path = os.path.join(root, item)
        if item == cook_folder_name:
            yield item_path
        elif os.path.isdir(item_path):
            yield get_one_cage(item_path, cook_folder_name)

程序执行结果如下:

在这里插入图片描述

显然是返回了一个迭代器,不是一个str,其逻辑如下图所示:

在这里插入图片描述

就好比,本意是:
小明把沙袋传给小红,小红传给小兰
但现在是:
小明把沙袋传给了小红,小红被传了出去
修改如下:

def get_one_cage(root: str, cook_folder_name: str):
    for item in os.listdir(root).copy():
        item_path = os.path.join(root, item)
        if item == cook_folder_name:
            yield item_path
        elif os.path.isdir(item_path):
            yield next(get_one_cage(item_path, cook_folder_name))

逻辑如下:

在这里插入图片描述

还有一种情况是学长源码里的:使用for调用迭代器:

def get_one_cage(root: str, cook_folder_name: str):
    for item in os.listdir(root).copy():
        item_path = os.path.join(root, item)
        if item == cook_folder_name:
            yield item_path
        elif os.path.isdir(item_path):
             for i in get_one_cage(item_path, cook_folder_name):
                 yield i

这使用于多个文件的返回,源码里还配合isfile使用,这里是简化版,所以显得冗余。
两种方式均可以正常使用。

昨天这篇文章写完后,遇到了bug,简单说就是,如果一个文件夹系统没有我们想要的文件,递归到最深一层文件夹时,会报错

在这里插入图片描述

1
可以理解为:老板让员工找一样东西,员工外包给编外人员。如果编外人员找到了想要的东西,一路传递回去,可以正常交差。如果没找到,编外人员就会一直找,不停歇,找遍了所有能找到的地方(遍历完整个文件夹)也没能找到,就会报错StopIteration。
因此,问题核心是,没有一个返回机制。修改办法是在遍历最后加一个空返回

def get_one_cage(root: str):
    for index, item in enumerate(os.listdir(root)):
        item_path = os.path.join(root, item)
        if item == 'cooked_xyz':
            yield item_path
        elif os.path.isdir(item_path):
            yield next(get_one_cage(item_path))
        elif index == len(os.listdir(root).copy()) - 1:
            yield

或者是利用try… except语句处理异常:

def get_one_cage(root: str):
    try:
        for item in os.listdir(root):
            item_path = os.path.join(root, item)
            if item == 'cooked_xyz':
                yield item_path
            elif os.path.isdir(item_path):
                yield next(get_one_cage(item_path))
    except:
        yield

在这里插入图片描述

会有如上报错,正常。
最后的yield换成return也是可以的,但最好还是用yield,两个混起来用怪怪的。

个人推荐第二种方法
注:copy()可以不用要

以上就是Python编程如何在递归中使用迭代器的详细内容,更多关于Python编程递归中使用迭代器的资料请关注其它相关文章!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们