Python - 字典键的累积均值


当需要计算字典键的累积均值时,会创建一个空字典,并对原始字典进行迭代,并访问其项。如果它存在于字典中,则该键将附加到空字典中,否则该值将取代该键。

示例

下面是相同内容的演示

from statistics import mean my_list = [{'hi' : 24, 'there' : 81, 'how' : 11}, {'hi' : 16, 'how' : 78, 'doing' : 63}] print("The list is : ") print(my_list) my_result = dict() for sub in my_list: for key, val in sub.items(): if key in my_result: my_result[key].append(val) else: my_result[key] = [val] for key, my_val in my_result.items(): my_result[key] = mean(my_val) print("The result is : ") print(my_result)

输出

The list is :
[{'hi': 24, 'there': 81, 'how': 11}, {'hi': 16, 'how': 78, 'doing': 63}]
The result is :
{'hi': 20, 'there': 81, 'how': 44.5, 'doing': 63}

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 导入了所需的包。

  • 定义了字典值列表,并显示在控制台上。

  • 定义了一个空字典。

  • 对原始字典值的列表进行了迭代,并获得了其项。

  • 如果这个键存在于字典中,则将其添加到空字典中。

  • 否则,此键将转换为值。

  • 再次迭代键和值,并使用“mean”方法获得它们的平均值。

  • 输出显示在控制台上。

更新于:20-Sep-2021

237 次浏览

开启你的职业生涯

通过完成课程获得认证

开始吧
广告