簡體   English   中英

Python - 迭代嵌套對象

[英]Python - Iterating over nested objects

在 Python 中迭代嵌套的 object 的優雅方法是什么? 我目前正在使用嵌套循環,如下所示。

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

有沒有更好的方法更 Pythonic?

您可以設置鏈式生成器以降低縮進級別。

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循環命名。

它是 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

但是不,這種概括並沒有使它更pythonic。 它只是避免過度縮進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM