按前3个条目的平均值对每个用户列表进行排序

时间:2015-04-27 20:13:37

标签: python sorting top-n

我有一些数据,这是各个用户的分数列表。 以下代码查找用户最后三个分数的最大值(排序以便首先显示分数最低的用户),然后将其打印出来:

dlist = {c:max(d[c][-3:]) for c in d} #max for each user from last 3
itmlist = sorted(dlist.items(), key=lambda x: x[1]) #sort items
for z in itmlist:
  print('{}: {} '.format(z[0], z[1])) #print user-by-user

我正在尝试修改它以使用sum(l)/len(l)来查找每个用户的最后三个分数的平均值,然后对其进行排序以按顺序打印最低用户平均值,但是已达到死路一条。

有人能指出我正确的方向吗?

-

编辑:

这是用于生成列表的代码。我使用的文本文件包含的数据包含以下格式的分数:

鲍勃:2
约翰:7

然后使用以下方法阅读:

[查看帖子历史记录]

4 个答案:

答案 0 :(得分:1)

问题有点不清楚,所以我做了一些假设,告诉我在某处是否错了?

OPENSHIFT_NODEJS_PORT

答案 1 :(得分:0)

defaultdict,deque和statistics.mean将执行您想要的操作:

from collections import defaultdict, deque
from statistics import mean

# store maximum three scores using a defaultdict for repeated keys
d = defaultdict(lambda: deque(maxlen=3))

for q in range(1, 4):
    with open('Group{}.txt'.format(q), 'r') as f:
        for record in f:
            x, y = record.split(':')
            d[x].append(int(y))

# sort by values
srt = sorted(d.items(), key=lambda x: x[1])

# print name and mean from sorted list
for name,scores in srt:
    print('{}: {} '.format(name, mean(scores))) #print user-by-user

如果要将值设置为平均值,请在排序前更新dict:

for name, scores in d.items():
    d[name] = mean(scores)


for name, mn in sorted(d.items(), key=lambda x: x[1]):
    print('{}: {} '.format(name, mn))

您不需要计算要排序的平均值,因为所有值的长度都是3,因此总得分最高的列表将具有最高的平均值。

答案 2 :(得分:0)

>>> d = {'Bob':[2,4,4,5], 'John':[7,5,5,1]}
>>> dlist = {c:max(d[c][-3:]) for c in d}
>>> dlist2 = {user:sum(scores[-3:])/3 for user,scores in d.items()}
>>> print(*(': '.join(map(str, [person, dlist2.get(person)])) for person in sorted(dlist2, key=dlist.get)), sep='\n')
John: 3.6666666666666665
Bob: 4.333333333333333

答案 3 :(得分:-2)

如果你只关心最后三个分数的平均值:

dlist = {c:sum(d[c][-3:]) for c in d} #sum of last three scores for each user
itmlist = sorted(dlist.items(), key=lambda x: x[1]) #sort items on score
for z in itmlist:
  print('{}: {} '.format(z[0], z[1]/3)) #print user-by-user