Python,将.txt文件的分数从最高到最低排序

时间:2016-05-03 21:33:24

标签: python sorting

我已经成功对我的节目进行了编码,以便对该节目进行排序'在文本文件中按字母顺序排列。

#Sort Alphabetically
with open(current_class, 'r') as f:
    StudentList = f.readlines()
    for line in sorted(StudentList):
        print(line.rstrip())

您能否提供我用于从最高到最低分数排序的密钥?我也相信' reverse = True'从最高到最低排序时。

我还将提供我用来保存每个学生的最后三个分数的代码,我的测验是否可以证明是否有任何帮助。

current_class = Classes[student_class]
class_format = "{} scored {}".format(name, Score)

users = defaultdict(lambda:deque([], maxlen=3))
with open(current_class) as f:
    for line in f:
        student, grade = line.split(' scored ')
        users[student].append(int(grade))

users[name].append(Score)

with open(current_class, 'w') as f: 
    for user, scores in users.items():
        for score in scores:
            class_format_updated = "{} scored {}\n".format(user, Score)
            f.write(class_format_updated)

1 个答案:

答案 0 :(得分:1)

您只需添加一个步骤,将输入解析为浮点数。

with open(current_class, 'r') as f:
    studentList = f.readlines()

    # this will sort the list based on the float that comes after " scored "
    studentList.sort(key = lambda line: float(line.split(" scored ")[-1]))

    for score in reversed(studentList):
        print(score)

更新

如果我理解你的后续评论和输入文本的结构,那么这应该有效:

Use of uninitialized value $port in hash element at ./test3.prg line 26, <LOG> line 1.
Use of uninitialized value $port in hash element at ./test3.prg line 26, <LOG> line 2.
Use of uninitialized value $port in hash element at ./test3.prg line 26, <LOG> line 3.
Use of uninitialized value $port in hash element at ./test3.prg line 26, <LOG> line 4.
AttemptsOnIP
181.3.202.142,1
183.3.202.172,18

Port,Status,AttemptOnPort,AttemptsOnIP,Malicious
15853,failed,4,1,
15853,succeeded,4,1,
18693,failed,1,1,
18942,failed,1,1,
18942,succeeded,1,1,
31130,succeeded,1,1,
43041,failed,1,1,
43041,succeeded,1,1,
44444,failed,1,1,
46321,failed,1,1,
46321,succeeded,1,1,
47417,failed,3,1,
47417,succeeded,3,1,
48713,failed,1,1,
48713,succeeded,1,1,
53653,failed,1,1,
53653,succeeded,1,1,
60563,failed,1,1,
60563,succeeded,1,1,
15853,failed,4,18,
15853,succeeded,4,18,
18693,failed,1,18,
18942,failed,1,18,
18942,succeeded,1,18,
31130,succeeded,1,18,
43041,failed,1,18,
43041,succeeded,1,18,
44444,failed,1,18,
46321,failed,1,18,
46321,succeeded,1,18,
47417,failed,3,18,
47417,succeeded,3,18,
48713,failed,1,18,
48713,succeeded,1,18,
53653,failed,1,18,
53653,succeeded,1,18,
60563,failed,1,18,
60563,succeeded,1,18,