Python列表中两个字典值的最大平均值

2024-10-02 00:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的字典列表:

array_of_dictionaries = [{
    "name": "Budi",
    "age": 23,
    "test_scores": [100.0, 98.0, 89.0]
},
{
    "name": "Charlie",
    "age": 24,
    "test_scores": [90.0, 100.0]
}]

这是我的代码:

def get_all_time_max_avg_score(dictionary_list):
  for element in dictionary_list:
    lensum = len(element['test_scores'])
    elesum = sum(element['test_scores'])
    meansum = elesum / lensum
    for attribute in element.keys():
        print("Mr. " + str(element['name']) + " with age(years) " + str(element['age']) + " get the highest average scores, " + str(round(meansum, 2)))
        break
get_all_time_max_avg_score(array_of_dictionaries)

所以我想从这两本字典中得到最高的平均分。我想要的输出是:

Mr. Budi with age(years) 23 get the highest average scores, 95.67

但我得到的是:

Mr. Budi with age(years) 23 get the highest average scores, 95.67
Mr. Charlie with age(years) 24 get the highest average scores, 95.0

我真的很感激能得到的每一个帮助


Tags: thenametestageget字典withelement
3条回答

这段代码迭代并打印列表中的每个元素。 相反,通过与平均值进行比较,对列表执行max

max(iterable, *, default=None, key=func)

下面是一个具有列表理解功能的解决方案。

def get_all_time_max_avg_score(dictionary_list):
    text = "Mr. {name} with age(years) {age} get the highest average scores, {average:.2f}"

    def average(element):
        return sum(element['test_scores']) / len(element['test_scores'])

    e = max((element for element in dictionary_list), key=average, default=0)
    return text.format(name=e['name'], age=e['age'], average=average(e))


print(get_all_time_max_avg_score(array_of_dictionaries))

产出:

Mr. Budi with age(years) 23 get the highest average scores, 95.67

在打印任何内容之前,您需要计算每一项的平均值

def get_all_time_max_avg_score(dictionary_list):
    for element in dictionary_list:
        lensum = len(element['test_scores'])
        elesum = sum(element['test_scores'])
        element['mean'] = elesum / lensum

    first = sorted(dictionary_list, key=lambda x: x['mean'], reverse=True)[0]

    print("Mr.", first['name'], "with age(years)", first['age'], "get the highest average scores,",
          round(first['mean'], 2))

或者使用Dataframe

def get_all_time_max_avg_score(dictionary_list):
    df = pd.DataFrame(dictionary_list)
    df['mean'] = df['test_scores'].apply(np.mean)
    first = df.loc[df['mean'].idxmax()]
    print("Mr.", first['name'], "with age(years)", first['age'],
          "get the highest average scores,", round(first['mean'], 2))

使用带有自定义键的内置max函数查找平均分数最高的条目

array_of_dictionaries = [{
    "name": "Budi",
    "age": 23,
    "test_scores": [100.0, 98.0, 89.0]
},
{
    "name": "Charlie",
    "age": 24,
    "test_scores": [90.0, 100.0]
}]

all_time_max_avg_score = max(
    array_of_dictionaries,
    key=lambda d: sum(d['test_scores']) / len(d['test_scores'])
)
meansum = sum(all_time_max_avg_score['test_scores']) / len(all_time_max_avg_score['test_scores'])

print("Mr. " + str(all_time_max_avg_score['name']) + " with age(years) " + str(all_time_max_avg_score['age']) + " get the highest average scores, " + str(round(meansum, 2)))

相关问题 更多 >

    热门问题