2016-04-15 6 views
-1

名前ごとに平均と最高スコアを計算しました。しかしながら。私は、テキストファイルに保存され、次の値を持っている場合、これは結果は何である:(?二度すなわちマットの平均値を、それをループ)最後の3つ以上のスコアを使用してデータを分析します。また分析を繰り返す?

matt 5 
matt 2 
matt 3 
andy 1 
andy 2 
andy 3 
andy 4 
matt 4 
matt 's average from the last 3 scores is 4.0 
andy 's average from the last 3 scores is 4.0 
matt 's average from the last 3 scores is 4.0 
andy -'s best score is 4 
matt -'s best score is 5 

それは、最初の名前を繰り返しているように見える また、それが生産されます最後の3つだけでなく、各スコアに基づいたデータ?

user_scores = {} 
for line in reversed(open("Class1.txt").readlines()): 
    name, score = line.split() 
    score = int(score) 
+0

データを作成するためのツリーメソッドを使用します。 'ast.literal_eval(line.strip()) 'と一緒に使うことができます – dsgdfg

+0

ありがとうございました! – Canadian1010101

+0

出力を名前、または数値(最高得点/平均)でアルファベット順にソートしますか? –

答えて

0

インデントエラーです。あなたは以下のこのブロックは最初のインデントレベルになりたい:

for name in sorted(user_scores): 
    # get the highest score in the list 
    average = sum(user_scores[name]) /float(len(user_scores[name])) 
    print(name, "'s average from the last 3 scores is", average) 

また、あなたのコードが悪い方法で書かれている多くの場所があります。

user_scores = {} 

# 'with' will automatically closes the file after leaving its code block: 
with open("Class1.txt") as scorefile: 

    for line in reversed(scorefile.readlines()): 
     name, score = line.split() 

     # nested if inside if/else is better than if-and plus if not: 
     if name in user_scores: 
      if len(user_scores[name]) < 3: 
       user_scores[name].append(int(score)) 
     else: 
      user_scores[name] = [int(score)] 

# If you want to sort by the numeric value, replace 'sorted(user_scores)' with 
# 'sorted(user_scores, key=lambda k: user_scores[k])': 
for name in sorted(user_scores): 
    # in Python 3 the '/' operator always returns the appropriate format. 
    # to get a pure integer division without decimal places, you would use '//'. 
    # Therefore no need for the float(...) conversion. 
    average = sum(user_scores[name])/len(user_scores[name]) 
    # str.format(...) is more flexible than just printing multiple items: 
    print("{}'s average from the last 3 scores is {}".format(name, average)) 

# No need to store another dictionary with best scores. 
# If you want to sort by the numeric value, replace 'sorted(user_scores)' with 
# 'sorted(user_scores, key=lambda k: user_scores[k])': 
for name in sorted(user_scores): 
    print("{}'s best score is {}".format(name, max(user_scores[name]))) 
+0

33行目にエラーメッセージが表示されます。逆順の行(スコアファイル)の場合: TypeError:反転する引数はシーケンスである必要があります – Canadian1010101

+0

@ Canadian1010101申し訳ありませんが、私の間違いです。そこにreadlines()が必要です。私の答えでそれを訂正しました。 –

+0

Iveはそれをテストし、最後の3つのスコアではなくすべてのスコアをカバーするので、平均スコアと最高スコアがすべてのスコアに終わるでしょうか? – Canadian1010101

関連する問題