簡體   English   中英

消除 Python 中的縮進

[英]Eliminate Indentations in Python

我正在使用 Google Docs API 來檢索文檔的內容並使用 Python 對其進行處理。 但是,該文檔結構復雜,我必須遍歷返回的 JSON 的多個節點,因此我必須使用多個 for 循環來獲取所需的內容並進行必要的過濾。 有沒有辦法可以消除一些縮進,使格式看起來更有條理?

這是我的循環片段:

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 循環,我希望我也可以刪除一些縮進。

任何幫助表示贊賞::)

減少縮進級別的一般方法是在自己的函數中將代碼塊標識為 go。

例如,看着你的循環,我想我會嘗試這樣的事情:

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”反模式

我對 python 沒有那么有經驗,但我很確定每個縮進只能使用一個空格而不是四的倍數,這不會是縮進錯誤。 雖然它不是根據 PEP 8 協議...所以只需將這組代碼中的每 4 個空格/制表符刪除到 1 個空格。

暫無
暫無

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

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