Python编程如何在递归函数中使用迭代器

作者:frank_haha 时间:2023-08-04 11:20:24 

首先,想要实现的功能是递归遍历文件夹,遇到满足条件的文件时,用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只能返回一层。如下图所示:

Python编程如何在递归函数中使用迭代器

综上两点作出如下修改:


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)

程序执行结果如下:

Python编程如何在递归函数中使用迭代器

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

Python编程如何在递归函数中使用迭代器

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


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))

逻辑如下:

Python编程如何在递归函数中使用迭代器

还有一种情况是学长源码里的:使用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,简单说就是,如果一个文件夹系统没有我们想要的文件,递归到最深一层文件夹时,会报错

Python编程如何在递归函数中使用迭代器

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

Python编程如何在递归函数中使用迭代器

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

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

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

来源:https://blog.csdn.net/frank_haha/article/details/120383940

标签:Python,递归函数,迭代器
0
投稿

猜你喜欢

  • Javascript中作用域的详细介绍

    2024-04-18 10:02:09
  • python中str内置函数用法总结

    2022-06-23 10:22:45
  • Python制作摩斯密码翻译器

    2021-06-27 15:27:58
  • 详解python中的三种命令行模块(sys.argv,argparse,click)

    2021-04-24 12:57:10
  • 使用MySQL实现select into临时表的功能

    2024-01-25 01:14:53
  • Python给你的头像加上圣诞帽

    2023-08-28 11:30:41
  • 浅谈MySQL中group_concat()函数的排序方法

    2024-01-22 09:21:12
  • MySQL 导出数据为csv格式的方法

    2024-01-26 04:52:57
  • Python函数参数类型及排序原理总结

    2021-12-29 05:12:10
  • python列表倒序的几种方法(切片、reverse()、reversed())

    2022-01-28 02:46:52
  • asp如何取回已忘记的密码?

    2010-05-13 16:33:00
  • python入门:argparse浅析 nargs='+'作用

    2023-06-26 15:52:58
  • 从头学Python之编写可执行的.py文件

    2022-07-10 18:47:29
  • python密码学简单替代密码解密及测试教程

    2023-09-30 08:13:00
  • python中的GUI实现计算器

    2022-04-18 02:29:05
  • MySQL最好的优化技巧

    2009-10-27 12:05:00
  • python 简易计算器程序,代码就几行

    2021-05-23 22:28:32
  • keras和tensorflow使用fit_generator 批次训练操作

    2023-04-09 04:55:59
  • python实现LBP方法提取图像纹理特征实现分类的步骤

    2023-05-24 02:12:27
  • 不要用强制方法杀掉python线程

    2021-04-10 09:19:18
  • asp之家 网络编程 m.aspxhome.com