Python-遍历嵌套对象

时间:2020-06-02 05:06:31

标签: python

在Python中迭代嵌套对象的一种优雅方法是什么?我目前正在使用嵌套循环,如下所示。

for job in jobs:
    for task in job.tasks:
        for command in task.commands:
            print command.actual_cmd

是否有更好的方法使用Pythonic?

2 个答案:

答案 0 :(得分:3)

您可以设置链接生成器以降低压痕级别。

iter_tasks = (task for job in jobs for task in job.tasks)
iter_commands = (command for task in iter_tasks for command in task.commands)

for command in iter_commands:
    print(command.actual_cmd)

我同意OldBunny2800的观点,在三个嵌套循环的情况下,链接生成器在可读性方面可能不会给您带来太多好处。

如果您的嵌套逻辑比这更深入,生成器将开始变得有吸引力。不仅可以控制缩进级别,还可以为每个生成器分配一个有意义的变量名称,从而有效地为for循环指定一个名称。

答案 1 :(得分:3)

这是pythonic 。已经。

但是,如果您担心这会深入到10多个级别,并且只有最里面的循环有什么有趣的事情,您可以考虑的一件事就是创建一个生成器。您的代码可以成为:

def get_command(jobs):
    for job in jobs:
        for task in job.tasks:
            for command in task.commands:
                yield command

for command in get_command(jobs):
    print command.actual_cmd

所以整个目的是避免过度缩进。

要使其在多个级别通用,因此即使深度超过100级别,您也不必担心:

def get_nested(objlist, attribs):
    for x in objlist:
        if len(attribs) == 0:
            yield x
        else:
            x_dot_attr = getattr(x, attribs[0])
            for y in get_nested(x_dot_attr, attribs[1:]):
                yield y

for command in get_nested(jobs, ["tasks", "commands"]):
    print command.actual_cmd

但是,不,这种概括并没有使其更具Python风格。这样只会避免过度缩进。