我正在嘗試迭代 JSON 檔案及其元素。問題是如果第一次迭代(元素)的值是 bool/float/int 或 NoneType 型別,則會拋出錯誤訊息。
這是我的嘗試(它適用于 bool、float 和 int,但拋出 TypeError: 'NoneType' object is not iterable):
for element in json:
if type(element) != bool \
and type(element) != float \
and type(element) != int \
and type(element) is not None:
for value in json[element]:
print(value)
有沒有辦法縮短 Python 中的代碼?
uj5u.com熱心網友回復:
在 Python 中,它的常見做法是執行它并處理任何例外。
for element in json:
try:
for value in element:
print(value)
except TypeError:
pass
另外,您確定要迭代json[element]還是要element在內部 for 回圈中迭代?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/329728.html
上一篇:如何在python上將一組值重新排列為新模式并列印結果
下一篇:同時分別打開、寫入和保存多個檔案
