【问题标题】:How to find an average of a key with multiple values?如何找到具有多个值的键的平均值?
【发布时间】:2015-02-23 18:28:34
【问题描述】:

我正在尝试按从高到低的顺序打印平均值,但是到目前为止我所拥有的代码是每个人的平均值,但是我无法按照从高到低的顺序打印它们。我尝试使用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

名称是键,分数是值。如果需要,我可以发布拆分循环。所以字典的打印结果如下:

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

【问题讨论】:

  • d 长什么样子?可以举个例子吗?
  • 您不能将相同的Louie Scored 字符串作为同一个字典的不同键。你能粘贴print dictionary的输出吗?

标签: python max average


【解决方案1】:

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

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并在那个dict上调用items(),你会得到一个更短的东西(以避免middle字典)。 2 元素元组,其中元组的第一个元素是键(您的 用户名),第二个元素是值(用户名的分数)。当您使用dictionary.items() 调用sorted 时,lambda 将接收那些 2 元组元素,因此在lambda x 中,x 将是一个元组,其中第一个元素 (x[0]username 和第二个元素 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

【讨论】:

  • 感谢您不仅帮助我找出问题,而且还如此详细地解释它:)
  • 很高兴我能帮上忙。玩得开心编码 :-)
【解决方案2】:

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

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

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

您可以将第一个元素设为平均值,然后您就不需要提供密钥

【讨论】:

  • 有没有办法不使用lambada函数?
  • 一定要写一个非 lambda 函数,或者使用operator.itemgetter 或者将平均值作为元组中的第一个值......而不是第二个
猜你喜欢
  • 1970-01-01
  • 2022-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多