2016-05-03 12 views
-1

アルファベット順にテキストファイルの「スコア」をソートするようにプログラムを正常にコーディングしました。Pythonは、.txtファイルのソートスコアが最高から最低まで

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

あなたは私が最高から最低までのスコアをソートするために使用するキーを私に提供することができますか?私はまた、最も低いものから最も低いものをソートするとき、「逆=真」と信じています。

私は、各生徒の最後の3つの得点を保存して、それが何らかの助けとなるかどうかを確認するために使用するコードも提供します。

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

入力をフロートとして解析するステップを追加することができます。

with open(current_class, 'r') as f: 
    studentList = [float(line) for line in f.readlines()] 
    for score in reversed(sorted(studentList)): 
     print(score) 

アップデート:私はあなたのフォローアップのコメント、正しく入力されたテキストの構造を理解していれば

が、これは動作するはずです:

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) 
+0

あなたが見ることができるように、私のプログラムの出力を(」 {}スコア付き{} \ n).format(名前、スコア)。それはそれほど単純ではありません。私は「スコアリング」を分割する必要がありますか?もしそうなら、第2の '{}'の後に '\ n'はどうなるでしょう。 –

+0

私は参照してください。私は入力テキスト構造の私の理解に基づいて応答を更新しました。 – Christian

+0

ありがとうございます!最後のこと!!ユーザーのすべてのスコアを平均値に並べ替えるには、キーで何が変更されますか? –

関連する問題