消除 Python 中的缩进

Eliminate Indentations in Python

我正在使用 Google 文档 API 检索文档的内容并使用 Python 对其进行处理。但是,文档结构复杂,我必须遍历返回的 JSON 的多个节点,所以我必须使用 multiple for loops 来获取所需的内容并执行必要的过滤器。有什么方法可以消除一些缩进,使格式看起来更有条理吗?

这是我的循环片段:

for key, docContent in docs_api_result.json().items():
    if key == "body":
        content = docContent['content']
        for i, body_content in enumerate(content):
            if "table" in body_content:
                for sKey, tableContent in content[i]['table'].items():
                    if sKey == "tableRows":
                        for tableRowContent in tableContent:
                            for tableCellMain in tableRowContent['tableCells']:
                                for tableCellContent in tableCellMain['content']:
                                    hasBullet = False
                                    for tableCellElement in tableCellContent['paragraph']['elements']:
                                        if "bullet" in tableCellContent['paragraph']:
                                            ...

我知道,而不是

if True:
    # some code here

我可以换成

if False:
    continue
# some code here

删除一些缩进,但这只能解决部分问题。我还有 7 个 for 循环,我希望我也可以删除一些缩进。

感谢任何帮助! :)

我对 python 没有那么多经验,但我很确定您每次缩进只能使用一个 space 而不是四个的倍数,这不会是缩进错误。虽然它不符合 PEP 8 协议...... 所以只需删除这堆代码中的每 4 spaces/tab 个,到 1 space.

减少缩进级别的一般方法是识别代码块以放入它们自己的函数中。

例如看看你的循环,我想我会尝试类似的东西:

class ApiResultProcessor(object):
    def process_api_result(self, api_result):
        doc_dict = api_result.json()
        if "body" in doc_dict:
            self.process_body(doc_dict["body"])

    def process_body(self, body_dict):
        content = body_dict["content"]
        for i, content_element_dict in enumerate(content):
            if "table" in content_element_dict:
                self.process_table(content_element_dict["table"])
        ...
    

    def process_table(self, table_dict):
        for tableRowContent in table_dict["tableRows"]:
            for tableCellMain in tableRowContent["tableCells"]:
                for tableCellContent in tableCellMain['content']:
                    self.process_cell_content(tableCellContent)

    def process_cell_content(self, table_cell_dict):
        hasBullet = False
        for tableCellElement in table_cell_dict["paragraph"]["elements"]:
            if "bullet" in table_cell_dict["paragraph"]:
                ...

我所做的唯一重构是试图避免可怕的 "for if" antipattern