使用 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