排序列表从最高到最低并定义变量

时间:2016-01-31 19:55:02

标签: python list sorting

这是我的代码,如何在最后更新name_scores,以便稍后(使用全局)可以在订购时调用它。

with open(class_number, "r") as file: #1
    file.seek(0) #2
    scores = file.readlines() #3
    name_scores = { } #4
    for line in scores: #5
        name, score = line.rstrip('\n').split(':') #6
        score = int(score) #7
        if name not in name_scores: #8
            name_scores[name] = []   #9    # Initialize score list
        name_scores[name].append(score) #10  # Add the most recent score
        if len(name_scores[name]) > 3:   #11
            name_scores[name].pop(0)   #12 

当我在功能外尝试print(name_scores)时 我明白了:

NameError: name 'name_scores' is not defined

但我不知道它是不是" name_scores"我想打印

我试图按字母顺序将最后三个分数从最高到最低排序

with open(view_class, "r") as file: #1
    for name in sorted(name_scores): #16
        name_scores = (sort(name_scores, reverse = True))
        print(name, '-', name_scores[name])

0 个答案:

没有答案