python - 在 Python 中递归遍历列表的子项

标签 python recursion

我尝试从嵌套的列表列表中递归打印句子

我想获取包含的列表

['大坏狗'、'毛茸茸的大猫'、'蓝色快乐小马'、'小 Frog ']

这是我的代码,它不起作用......

我是否走在正确的道路上,或者我应该以另一种方式构建数据以实现我的目标?

from pprint import pprint

dirs = [

{ 
    'kw': 'big',
    'childs': [
        { 
            'kw': 'bad',
            'childs': [
                {
                    'kw': 'dog'
                }
            ]
        },
        {
            'kw': 'fluffy',
            'childs': [
                {
                    'kw': 'cat'
                }
            ]
        }

    ]
},

{ 
    'kw': 'small',
    'childs': [
        { 
            'kw': 'blue',
            'childs': [
                {

                    'kw': 'happy',
                    'childs': [
                        { 
                            'kw': 'pony'

                        }

                    ]
                }
            ]
        },
        {
            'kw': 'frog'

        }

    ]
},
]


def traverse(d, l):

    kw = d.get('kw')
    c = d.get('childs')
    l.append(kw)
    if c:
        for cc in c:
           l = traverse(cc, l)



return l


r = traverse(dirs[0], [])

pprint(r)

最佳答案

像往常一样,生成器可以很好地与递归结构配合使用

def traverse(i):
    for d in i:
        childs = d.get('childs')
        for j in traverse(childs) if childs else ['']:
            yield d['kw']+' '+j

res = list(traverse(dirs))

在Python3.3中,这变成了

def traverse(i):
    for d in i:
        c = d.get('childs')
        yield from (d['kw']+' '+j for j in (traverse(c) if c else ['']))

关于python - 在 Python 中递归遍历列表的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18265961/

相关文章:

powershell - 无法从 Python 项目中递归删除 pyc 文件

python - sqlalchemy中的连接池是线程安全的吗?

python - 重构序数打印算法

python - 打印一行数字,然后换行继续计数

javascript - 用连字符替换字符串中的空格

haskell - Haskell中的整数平方根函数

python - 如何在Python中加载带有日期和时间的文件作为日期时间对象?

python - 使用 numpy 操作一个数组中的数据以影响另一个数组

function - 自定义 scala 递归预防机制的改进

java - 不同起点的八皇后算法