如何找到具有多个值的键的平均值?

How to find an average of a key with multiple values?

我正在尝试按从高到低的顺序打印出平均值,但是到目前为止,我的代码为每个人计算了平均值,但是我无法按从高到低的顺序打印出它们。我尝试使用 max 函数,但它不起作用。

for usernames, valuesforusers in sorted(dictionary.items()):
            thefirstaveragevariable = sum(valuesforusers)/len(valueforusers)
            averageslistofdoom = []
            averageslistofdoom.append(average)
            print ("{} Scoreino ploxerino thankerino: {}".format(usernames,max(averagesofdoom)))

字典会这样:

Thomas Scored: 8
Louie Scored: 3
Thomas Scored: 4
Louie Scored: 5
Louie Scored: 2

名字是键,分数是值。如果需要,我可以 post 拆分 loop.So 字典打印如下:

{'Louie Scored': [3, 5, 2], 'Thomas Scored': [8, 4]}

使用 numpy ...你还必须提供一个键来排序

import numpy as np
print sorted((username,np.average(values),values) for username, values in d.items(), key=lambda x:x[1])

默认排序将根据第一个元素对元组进行排序...在本例中是它们的名称。

您可以将第一个元素改为平均值,这样就不需要提供键

所以我要做的是用你的用户的平均值创建一个中间字典,然后显示排序。您可能想看看 operator.itemgetter and sorted 做了什么。

import operator

dictionary = {
    'Louie Scored': [3, 5, 2],
    'Thomas Scored': [8, 4]
}

averages = {}

for user_info, v in dictionary.items():
    average = float(sum(v))/len(v)
    averages[user_info] = average

sorted_averages = sorted(averages.items(), key=operator.itemgetter(1), reverse=True)
for user_name, average in sorted_averages:
    print ("{} average score {}".format(user_name, average))

输出:

Thomas Scored average score 6.0
Louie Scored average score 3.33333333333

如果你有一个 dict 并调用 items() 在那个 dict 上,你得到双元素元组,其中元组的第一个元素是键(你的 用户名 ),第二个元素是值(用户名的分数)。当您使用 dictionary.items() 调用 sorted 时,lambda 将接收那些二元组元素,因此在 lambda x 中,x 将是一个元组,其中第一个元素(x[0] 用户名 ,第二个元素 x[1] 是该用户名的分数):

dictionary = {
    'Louie Scored': [3, 5, 2],
    'Thomas Scored': [8, 4]
}

for username, values in sorted(dictionary.items(),
                               key=lambda x: (sum(x[1]) / len(x[1])), reverse=True):
    print "username: %s, values %s" % (username, sum(values) / len(values))

输出:

username: Thomas Scored, values 6
username: Louie Scored, values 3