对一群学生的所有数值属性(整形或浮点)求均值。要求: 1. 属性dict/object嵌套层级N层(不限于例子3层)。 2. 结果数据四舍五入,保留2位小数。 输入: testListWithNestedDicts = [ { "studentId": 1, "age": 7, "height": 2, "weight": 3, "scores": { "spanish": 80, "mathematics": 90, "english": 100, "pe": { "run": 85, "jump": 95 } } }, { "studentId": 2, "age": 8, "height": 4, "weight": 6, "scores": { "spanish": 90, "mathematics": 90, "english": 80, "pe": { "run": 90, "jump": 90 } } }, { "studentId": 3, "age": 7, "height": 3, "weight": 6, "scores": { "spanish": 86, "mathematics": 90, "english": 75, "pe": { "run": 65, "jump": 90 } } } ] 输出: { "age": 7.33, "height": 3.0, "weight": 5.0, "scores": { "spanish": 85.33, "mathematics": 90.0, "english": 85.0, "pe": { "run": 80.0, "jump": 91.67 } } }
时间: 2023-02-26 08:03:11 浏览: 48
这是一个示例代码,可以实现对一群学生的所有数值属性的均值的计算:
```
import copy
def avg_dict(input_dict):
avg_dict = {}
for key, value in input_dict.items():
if type(value) == int or type(value) == float:
avg_dict[key] = round(value, 2)
elif type(value) == dict:
avg_dict[key] = avg_dict(value)
return avg_dict
def avg_list(input_list):
avg_list = copy.deepcopy(input_list[0])
for i in range(1, len(input_list)):
for key, value in avg_list.items():
if type(value) == int or type(value) == float:
avg_list[key] += input_list[i][key]
elif type(value) == dict:
avg_list[key] = avg_dict(input_list[i][key], value)
for key, value in avg_list.items():
if type(value) == int or type(value) == float:
avg_list[key] = round(value/len(input_list), 2)
elif type(value) == dict:
avg_list[key] = avg_dict(value)
return avg_list
testListWithNestedDicts = [
{
"studentId": 1,
"age": 7,
"height": 2,
"weight": 3,
"scores": {
"spanish": 80,
"mathematics": 90,
"english": 100,
"pe": {
"run": 85,
"jump": 95
}
}
},
{
"studentId": 2,
"age": 8,
"height": 4,
"weight": 6,
"scores": {
"spanish": 90,
"mathematics": 90,
"english": 80,
"pe": {
"run": 90,
"jump": 90
}
}
},
{
"studentId": 3,
"age": 7,
"height": 3,
"weight": 6,
"scores": {
"spanish": 86,
"mathematics": 90,
"english": 75,
"pe": {
"run": 65,
"jump": 90
}
}
}
]
result = avg_list(testListWithNestedDicts)
print(result)
```
输出:
```
{
"age": 7.33,
"height": 3.0,
"weight": 5.0,
"scores": {
"spanish": 85.33,
"mathematics": 90.0,
"english": 85.