如何按升序对此浮动数值列表进行排序?

时间:2015-12-03 23:49:46

标签: python list sorting csv

我能够在CSV文件中为每个人导入3个分数(或数字) 并且计算出每个人的三个分数的平均值,但我接下来需要做的是将输出中显示的平均值列表从高到低排序。我到处搜索,并且在尝试的所有内容中都收到了“Float”错误。

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)

输出:

Odis 22.0
Vance 20.0
John 26.0
Marinda 25.0
Shenita 18.0
Marquitta 24.0
Concepcion 17.0
Robby 23.0
Valda 19.0
Ernesto 21.0
Jack 5.0

我的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

3 个答案:

答案 0 :(得分:3)

您不需要对平均排序的行 - 毕竟这些是单个人的分数,并且您按照它们的顺序排列并不重要。您要做的是在计算所有平均值后对所有条目进行排序,因此您需要收集这些条目。如果你希望它们根据它们的平均值进行排序,那么使用一个平均值作为第一个字段的元组,这样排序将完全符合你的要求:

# 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)

然而,更多的Pythonesque方式是使用列表推导:

# A function for the average
def average(lst):
    return sum(lst) / float(len(lst))

# The averages as list comprehension    
avgs = sorted((average(scores), name)
              for name, scores in user_scores.items())

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

这假定您使用的是Python 3,因为Python 2使用iteritems()viewitems()

答案 1 :(得分:1)

假设Python 3 ...

在您的第二个for循环中,如果您在仍在计算平均值时重新打印它们,则无法按所需顺序打印它们。您需要将其分为两个阶段。

计算平均分数:

avg_user_scores = {
    user: sum(map(float, 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)

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)

答案 2 :(得分:0)

平均每个人的三个分数。将值放入字典中(键将是人物)。调用sorted()方法。