我已经能够在我的CSV文件中为每个人导入3个分数(或数字) 让它计算出每个人三个分数的平均值,但接下来我要做的是将输出中显示的平均值从高到低排序。我到处找遍了,但我尝试的每件事都收到了“浮动”错误。在
from collections import defaultdict, deque
with open("highscores.csv", "r+")as file:
file.seek(0)
scores = file.readlines()
user_scores = defaultdict(lambda:deque(maxlen=3))
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
user_scores[name].append(score)
for name in user_scores:
avg = (user_scores[name])
x = sorted(avg)
avg2 = sum(x) / float(len(x))
print(name, avg2)
输出:
^{pr2}$我的CSV文件如下所示:
Jack 4
Jack 5
Jack 6
Concepcion 7
Shenita 8
Valda 9
Vance 10
Ernesto 11
Odis 12
Robby 13
Marquitta 14
Marinda 15
John 16
Concepcion 17
Shenita 18
Valda 19
Vance 20
Ernesto 21
Odis 22
Robby 23
Marquitta 24
Marinda 25
John 26
Concepcion 27
Shenita 28
Valda 29
Vance 30
Ernesto 31
Odis 32
Robby 33
Marquitta 34
Marinda 35
John 36
平均每人三分。将这些值放入字典(关键是person)。调用sorted()方法。在
Python假设3
在第二个
for
循环中,如果在计算平均值的同时打印它们,则不可能按所需的顺序打印它们。你需要把它分成两个阶段。在计算平均分:
然后按降序打印:
^{pr2}$operator.itemgetter(1)
是获取元组的第二个元素(即lambda t: t[1]
)的一种方法,即平均得分。在整个项目:
你把平均值排序的那一行是没有必要的——毕竟这些都是一个人的分数,你用什么顺序求和并不重要。您要做的是在计算所有平均值后对所有条目进行排序,因此您需要收集这些条目。如果要根据平均值对它们进行排序,请使用一个tuple,其中average作为第一个字段,这样sorted将完全满足您的需要:
然而,一种更为Python式的方法是理解列表:
^{pr2}$这假设您使用的是python3,而python2则使用}
iteritems()
或{相关问题 更多 >
编程相关推荐