如何按升序排列这个浮点数列表?

2024-10-02 00:39:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经能够在我的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

Tags: namefilescorejackuserscoresvancerobby
3条回答

平均每人三分。将这些值放入字典(关键是person)。调用sorted()方法。在

Python假设3

在第二个for循环中,如果在计算平均值的同时打印它们,则不可能按所需的顺序打印它们。你需要把它分成两个阶段。在

计算平均分:

avg_user_scores = {
    user: sum(map(float, scores))/len(scores)
    for user, scores in user_scores.items()
}

然后按降序打印:

^{pr2}$

operator.itemgetter(1)是获取元组的第二个元素(即lambda t: t[1])的一种方法,即平均得分。在


整个项目:

from collections import defaultdict, deque
from operator import itemgetter

user_scores = defaultdict(lambda: deque(maxlen=3))
with open('highscores.csv') as file:
    for line in file:
        name, score = line.split(',')
        user_scores[name].append(float(score))
avg_user_scores = {
    user: sum(scores) / len(scores)
    for user, scores in user_scores.items()
}
for name, score in sorted(avg_user_scores.items(), key=itemgetter(1), reverse=True):    
    print(name, score)

你把平均值排序的那一行是没有必要的——毕竟这些都是一个人的分数,你用什么顺序求和并不重要。您要做的是在计算所有平均值后对所有条目进行排序,因此您需要收集这些条目。如果要根据平均值对它们进行排序,请使用一个tuple,其中average作为第一个字段,这样sorted将完全满足您的需要:

# The list that will hold the pairs of
# average score and name
avgs = []

# Your initial loop
for name in user_scores:
    x = user_scores[name]

    # Just collect the pair
    avgs.append((sum(x) / float(len(x)), name)

# Now sort it
avgs = sorted(avgs)

# Print it
for avg, name in avgs:
    print (name, avg)

然而,一种更为Python式的方法是理解列表:

^{pr2}$

这假设您使用的是python3,而python2则使用iteritems()或{}

相关问题 更多 >

    热门问题