我正在使用GoogleDocsAPI检索文档的内容,并使用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没有太多的经验,但我非常确信,每次缩进只能使用一个空格,而不是四个空格的倍数,而且不会出现缩进错误。虽然它不符合PEP 8协议。。。 因此,只需删除这组代码中每4个空格/制表符,即1个空格
减少缩进级别的一般方法是识别代码块以用于它们自己的函数
例如,看着你的循环,我想我会尝试以下方法:
我所做的唯一重构就是试图避免可怕的"for if" antipattern
相关问题 更多 >
编程相关推荐