使用 Python 查詢巢狀記錄值的總和
問題陳述需要使用 Python 查詢巢狀記錄值的總和。有時我們需要新增資料中存在的值,因此在這種情況下,這種方法可能很有用,因為記錄是強大的資料集,可以透過鍵更新或操作資料。
理解問題
給定的問題是找到給定記錄中值的加和,因此這裡我們將使用巢狀字典作為記錄。我們將使用 Python 實現程式碼。
巢狀字典是指字典內部的字典。我們必須找到巢狀值並將它們加起來作為結果。
演算法 - 對記錄中所有存在的數值求和
步驟 1 − 定義名為 sum_record_values 的函式,並在該函式內部,我們將傳遞名為 the_record 的巢狀字典作為輸入。
步驟 2 − 初始化 sum 變數,我們將在其中儲存巢狀記錄中所有值的總和。
步驟 3 − 將為巢狀記錄中的所有鍵值對啟動一個迴圈。然後將啟動條件以驗證該值是否為數字,然後將該值新增到 sum 變數中。
步驟 4 − 如果巢狀記錄中存在整數,則遞迴呼叫上面建立的函式並將返回值新增到 sum 中。
示例
# Function to get the summation of values
def sum_record_values (the_record):
sum = 0
for value in the_record.values():
if isinstance(value, int):
sum += value
elif isinstance(value, dict):
sum += sum_record_values(value)
return sum
# input nested record
the_record = {
'A': 1,
'B': {
'C': 5,
'D': {
'E': 6,
'F': 5
}
},
'G': 7
}
# pass the input record and call the function
output = sum_record_values(the_record)
# show the output
print("The summation of nested record values:", output)
輸出
The summation of nested record values: 24
複雜度
上述函式 sum_record_values 的時間複雜度為 O(N),其中 N 是記錄中鍵值對的數量。
演算法 - 對記錄中相同鍵的值求和
步驟 1 − 將巢狀記錄初始化為 the_record。
步驟 2 − 然後,我們將初始化一個空記錄以儲存具有相同鍵的總和值。
步驟 3 − 然後將為 the_record 的值啟動迴圈。
步驟 4 − 在外部迴圈內部,我們將對子記錄項啟動另一個內部迴圈。
步驟 5 − 然後在內部迴圈中,當前項的值將新增到 sum_values 記錄中相應鍵中。
步驟 6 − 使用 print() 函式列印更新後的 sum_values 記錄。
示例
# Initialize the nested record
the_record = {
'Vegetable' : {'red' : 4, 'green' : 5, 'yellow' : 8},
'Fruits' : {'red' : 8, 'yellow' : 10},
'Dry_fruits' : {'yellow' : 19, 'green' : 10}
}
#Initialize the empty record as dictionary
record_values = dict()
for subdict in the_record.values():
for key, item in subdict.items():
record_values[key] = item + record_values.get(key, 0)
#Show the summation of nested record values with same key
print("The summation values : " + str(record_values))
輸出
The summation values : {'red': 12, 'green': 15, 'yellow': 37}
複雜度
上述程式碼用於查詢相同或相同鍵的總和所花費的時間為 O(nm)。其中 n 是外部記錄中的鍵數,m 是內部記錄中的鍵數。
結論
因此,我們已成功實現了使用 Python 查詢巢狀記錄值總和的程式碼。在本文中,我們看到了兩種方法,第一種方法是對記錄中存在的所有值求和,第二種方法是對相同的鍵值求和。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP