查詢 Python 中字典的深度
Python 字典可以巢狀,即在一個字典中存在字典。本文將探討在存在巢狀字典時如何計算字典的巢狀層級。
使用字串轉換
在此方法中,我們將整個字典轉換為字串。然後我們計算左大括號 { 的數量,該數量指示字典巢狀到哪個層級。
示例
dictA = {1: 'Sun', 2: {3: {4:'Mon'}}}
dictStr = str(dictA)
cnt = 0
for i in dictStr :
if i == "{":
cnt += 1
print("The depth of dictionary: ",cnt)輸出
執行上述程式碼得到以下結果 −
The depth of dictionary: 3
使用遞迴
我們可以設計一個函式,該函式將遞迴呼叫自身來檢查字典中的值。只要內部元素被評估為字典,該函式就會自身呼叫,並且我們將得到字典深度的結果。
示例
def finddepth(dictA):
if isinstance(dictA, dict):
return 1 + (max(map(finddepth, dictA.values()))
if dictA else 0)
return 0
dictA = {1: 'Sun', 2: {3: {4:'Mon'}}}
print("The depth of dictionary: ",finddepth(dictA))輸出
執行上述程式碼得到以下結果 −
The depth of dictionary: 3
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP