2016-02-29 66 views
2

我正在嘗試使用名爲「score.txt」的文本文件創建名稱和點的字典。 文件的內容stuctured這樣的:正在尋找提高的字典中的分數計算

Anders Johansson 1 
Karin Johansson 1 
Anders Johansson 2 
Eva Johansson 0 

+ 2000個名稱,並指出在總

我得到的分數,計算和尋找高得分的方法是這樣的

f = open('score.txt').read().split() 
d = {} 
for x in range(0, len(f), 3): 
    name, value = ' '.join([f[x], f[x+1]]), int(f[x+2]) 
    if(name in d): 
     d[name] += value 
    else: 
     d[name] = value 
print(max(d, key=d.get),d[max(d, key=d.get)]) 

我很新的Python,所以我正在尋找方法來提高我的代碼。

+0

這個問題很明確。你在做什麼?性能或代碼風格的改進?恐怕你不會得到這個問題的「正確」答案。 –

+0

查看[CodeReview](http://codereview.stackexchange.com/)。 – MSeifert

+2

這可能是Code Review的話題,只要** A **代碼有效**和B **,它無論如何都不是假想的或不完整的。如果您選擇去那裏,請在發佈之前閱讀主題指南。 – Quill

回答

2

它看起來已經不可太瘋狂了,但我有幾個建議:

  • 命名Python convention是描述性的名稱(得分,而不是d)。
  • File opening最好用with節。
  • 你可以遍歷行,所以你不需要range
  • 使用defaultdict所以你不需要在字典中測試存在。

這將產生:

from collections import defaultdict 

scores = defaultdict(int) 

with open('score.txt') as infile: 
    for line in infile: 
     fields = line.split() 
     name, score = ' '.join([fields[0], fields[1]]), int(fields[2]) 
     scores[name] += score 

print(max(scores, key=scores.get), scores[max(scores, key=scores.get)]) 
0

小的變化對您的代碼。這會稍微改善性能。

代碼:

from collections import defaultdict 

datas ="""Anders Johansson 1 
Karin Johansson 1 
Anders Johansson 2 
Eva Johansson 0""".split() 

dic = defaultdict(int) 

for i in range(0, len(f), 3): 
    name, value = ' '.join([datas[i], datas[i+1]]), int(datas[i+2]) 
    dic[name] += value 

max_key =max(dic, key=d.get) 
print(max_key, dic[max_key]) 

輸出:

('Anders Johansson', 3) 

注:

  • 既然你是愛上同一個參數TWI同樣的方法ce max(d, key=d.get)我已經將它存儲在一個變量中並重新使用它。
  • 由於詞典的價值只是我用整型defaultdict
0

唯一的語義問題,你的代碼可能會出現的是,如果你需要處理composite names,例如,畢加索。在這種情況下,程序將中斷。另外,如果你的文件很大,爲了提高性能會更好地在讀取文件時計算高分。我的疑慮在下面的代碼中處理:

from collections import defaultdict 

highScore = 0 
highScoreName = "" 
scores = defaultdict(int) 

with open('score.txt') as f: 
    for line in f: 
     fields = line.split() 
     name, score = ' '.join(fields[:-1]), int(fields[-1]) #Handle composite names 
     scores[name] += score 
     if scores[name] > highScore: #Compute high score 
      highScore, highScoreName = scores[name], name 

print highScoreName, highScore