社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何理解python中的嵌套生成器?

Prodiction • 5 年前 • 1572 次点击  

我有这个密码:

def flat_on_level1(it, d=-1, level=None):
    """

    >>> list(flat_on_level1([[[['a']]]], level=3))
    [['a']]

    """
    if d==-1:
        return list(flat_on_level1(it, d=d+1, level=level))

    if d==level:
        return (i  for i in [it])

    for x in it:
        yield from flat_on_level1(x, d=d+1, level=level)

def flat_on_level(it, d=-1, level=None):
    """
    >>> list(flat_on_level([[[['a']]]], level=3))
    [['a']]

    """
    if d == -1:
        return list(flatt_on_level(it, d=d + 1, level=level))

    if d == level:
        return (i for i in [it])

    res = []
    for x in it:
        res.extend( flat_on_level(x, d=d+1, level=level))
    return res

我得到一张空名单。这是怎么回事?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55411
 
1572 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Prodiction
Reply   •   1 楼
Prodiction    6 年前

所以,好吧,没有伟大的暗示的帮助,我必须这样做。它看起来是个不错的发电机。我的问题更多的是关于重新制定职能的策略,一个人可以屈服于一个简单的清单,而不是我具体做错了什么。

def flat_on_level(it, d=-1, level=None):
    """

    >>> list(flat_on_level([[[['a']]]], level=3))
    ['a']

    """
    if isinstance(it, dict):
        y = it.values()
    else:
        y = it
    if not isinstance(y, collections.Iterable):
        yield y
    else:
        for x in y:
            if d == level:
                yield x
            else:
                yield from flat_on_level(x, d=d + 1, level=level)
Alec Alameddine
Reply   •   3 楼
Alec Alameddine    6 年前

每次只返回一个值。你需要给收益率打电话,次数是你名单长度的两倍