如何在巢狀的 Python 字典中計數元素?
要計算巢狀字典中的元素,我們可以使用內建函式 len()。利用它,我們還可以使用一個遞迴呼叫並計算任意深度巢狀字典中元素的函式。
計算字典中的元素
讓我們首先建立一個 Python 字典,並使用 len() 方法計算其值。在這裡,我們在字典中包含了 4 個鍵值對並顯示它們。產品、型號、單位和可用是字典的鍵。除了“單位”鍵外,所有鍵都具有字串值。
示例
# Creating a Dictionary myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print(myprod) # Count print(len(myprod))
輸出
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
4
現在,我們將建立一個巢狀字典並計算元素。
計算巢狀字典中的元素
為了計算巢狀字典中的元素,我們使用了 sum() 函式,並在其中逐個計算字典的值。最後,顯示計數。
示例
# Creating a Nested Dictionary myprod = { "Product1" : { "Name":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" }, "Product2" : { "Name":"SmartTV", "Model": "LG", "Units": 70, "Available": "Yes" }, "Product3" : { "Name":"Laptop", "Model": "EEK", "Units": 90, "Available": "Yes" } } # Displaying the Nested Dictionary print("Nested Dictionary = \n",myprod) print("Count of elements in the Nested Dictionary = ",sum(len(v) for v in myprod.values()))
輸出
Nested Dictionary =
{'Product1': {'Name': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}, 'Product2': {'Name': 'SmartTV', 'Model': 'LG', 'Units': 70, 'Available': 'Yes'}, 'Product3': {'Name': 'Laptop', 'Model': 'EEK', 'Units': 90, 'Available': 'Yes'}}
Count of elements in the Nested Dictionary = 12
計算任意深度巢狀字典中的元素
為了計算任意深度巢狀字典中的元素,我們建立了一個自定義 Python 函式並在其中使用了 for 迴圈。迴圈遞迴呼叫並計算字典的深度。最後,它返回長度。
示例
# Creating a Nested Dictionary myprod = { "Product" : { "Name":"Mobile", "Model": { 'ModelName': 'Nord', 'ModelColor': 'Silver', 'ModelProcessor': 'Snapdragon' }, "Units": 120, "Available": "Yes" } } # Function to calculate the Dictionary elements def count(prod, c=0): for mykey in prod: if isinstance(prod[mykey], dict): # calls repeatedly c = count(prod[mykey], c + 1) else: c += 1 return c # Displaying the Nested Dictionary print("Nested Dictionary = \n",myprod) # Display the count of elements in the Nested Dictionary print("Count of the Nested Dictionary = ",count(myprod))
輸出
Nested Dictionary =
{'Product': {'Name': 'Mobile', 'Model': {'ModelName': 'Nord', 'ModelColor': 'Silver', 'ModelProcessor': 'Snapdragon'}, 'Units': 120, 'Available': 'Yes'}}
Count of the Nested Dictionary = 8
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP