递归式生成器

生成器返回是一个可迭代的对象

from collections.abc import Iterable
from collections.abc import Iterator
def diedai():
    a=[1,2,3,4,5]
    for i in a:
        yield i
a=diedai()
print(isinstance(a, Iterator))

在这里插入图片描述
注意:我在导入import Iterable和import Iterator警告DeprecationWarning: Using or importing the ABCs from ‘collections’ instead of from ‘collections.abc’,因为python3.8已经弃用从collections导入了,改为collections.abc导入
参考链接:https://blog.csdn.net/qq_38125058/article/details/86605232

在遇到这段代码的时候,很看不懂for element in yield_test(sublist) ,还有运行结果为什么到异常之后还会回到第二个for处
1.每一个递归在递的过程中运行到yield_test(sublist)都会暂停阻塞
2.比如列表[1,2],运行完第一个for之后,到第二个for处,调用yield_test函数,进入下一层,就会触发typeerror,因为for没法迭代一个数字,触发异常之后就会去运行异常步骤,yield nested生成一个1的迭代器,这个时候就会返回值到上一层,接着从暂停阻塞处执行,也就是第二个for处,接着执行接下来的步骤, yield element这个步骤再生成一个1,最后再在调用函数的地方用for迭代并打印出来

def yield_test(nested):
    try:
        for sublist in nested:
            print('第一个for')
            t=yield_test(sublist)  #这通过异常步骤返回的是个迭代器
            # print(t)
            for element in t:
                print('第二个for')
                # print(element)
                # pass
                yield element
    except TypeError:
        print('异常')
        # print(nested)
        yield nested

# print(yield_test([1,2]))

for i in yield_test([1,2]):
    print(i)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值