2016-04-15 52 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行收到錯誤消息:在逆轉(scorefile)線: 類型錯誤:參數逆轉()必須是一個序列 – Canadian1010101

+0

@ Canadian1010101對不起,我錯了。你需要readlines()。糾正了我的答案。 –

+0

我測試過它,它涵蓋了所有的分數,而不僅僅是最後三個分數,所以平均分和最高分都是最後得分。 – Canadian1010101