猿问

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

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


互换的青春
浏览 195回答 5
5回答

LEATH

此代码迭代并打印列表中的每个元素。相反,通过与平均值max比较来执行列表。最大(可迭代,*,默认=无,键=功能)这是一个列表理解的解决方案。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

慕勒3428872

在打印任何内容之前,您需要计算每一项的平均值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))或者使用Dataframedef 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))

30秒到达战场

使用带有自定义键的内置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)))

慕无忌1623718

收集所有名称的平均值并选择最大值def get_all_time_max_avg_score(dictionary_list):    means = []    for d in dictionary_list:        means.append(sum(d['test_scores']) / len(d['test_scores']))    maxmean = max(means)    winner = dictionary_list[means.index(maxmean)]    print(        f'Mr. {winner["name"]}, with {winner["age"]} years of age, has the ' +        f'highest average scores: {maxmean:.2f}'    )get_all_time_max_avg_score(array_of_dictionaries)输出Mr. Budi, with 23 years of age, has the highest average scores: 95.67

饮歌长啸

通过一些额外的循环,您可以确定具有最大平均值的人def get_all_time_max_avg_score(dictionary_list):     maxPersonIndex=0    maxAver=0    index=0    for element in dictionary_list:        lensum = len(element['test_scores'])        elesum = sum(element['test_scores'])        meansum = elesum / lensum        if(meansum>maxAver):            maxAver=meansum            maxPersonIndex=index        index+=1                for attribute in dictionary_list[maxPersonIndex].keys():        print("Mr. " + str(element['name']) + " with age(years) " + str(element['age']) + " get the highest average scores, " + str(round(meansum, 2)))        breakget_all_time_max_avg_score(array_of_dictionaries)
随时随地看视频慕课网APP

相关分类

Python
我要回答