2017-04-17 89 views
-3

的我有一個包含一個文本文件:計算基於索引

ROX:KT:3:2 
JAG:CJ:1:0 
KDO:MST:2:1 
KDO:ROX:1:3 
JAG:KT:2:1 

我要計算每個團隊總分。例如:

ROX:6 
JAG:3 
KDO:3 
MST:1 
KT: 3 

下面是我對工作的代碼:

fileName = input("Enter file name:") 
match = open(fileName) 
table = [] 

for line in match: 
    contents = line.strip() 
    table.append(contents) 

dictionary = {} 
for line in table: 
    teamA,teamB,scoreA,scoreB = line.split(':') 
    #I'm stuck here onwards 
    . 
    . 

從我能想到的,我不得不代碼蟒蛇,以確保同一團隊的指數對應的指數數字顯示在文本文件的其他部分,以便獲得總和。問候。

+3

[從分數計算勝場數]的可能的複製(http://stackoverflow.com/questions/43452802/calculating-number-of-wins-from -a-score) – eyllanesc

+1

您在概念上的問題類似於您以前的問題(http://stackoverflow.com/questions/43452802/calculating-number-of-wins-from-a-score/43452971#43452971)。 SO不是一個編程服務,所以我認爲它應該關閉。 – eyllanesc

回答

0

試試這個:

f = open('filename.txt').readlines() 

f = [i.strip('\n') for i in f] 


f = [i.split(':') for i in f] 



dct = {} 

for i in f: 
    for b in range(len(i[:2])): 
     if i[:2][b] not in dct.keys(): 
      dct[i[:2][b]] = int(i[2:][b]) 

     else: 
      dct[i[:2][b]] += int(i[2:][b]) 
print dct 
1

你可以這樣做,用collections.defaultdict

import collections 

fileName = input("Enter file name:") 
match = open(fileName) 
table = [] 

for line in match: 
    contents = line.strip() 
    table.append(contents) 

scores = collections.defaultdict(int) 
for line in table: 
    teamA,teamB,scoreA,scoreB = line.split(':') 
    # even if scores does not have the team key, += will create it 
    scores[teamA] += int(scoreA) 
    scores[teamB] += int(scoreB) 
+1

我剛剛用正常的內聯如果方法完成了我的解決方案,但defaultdict更好。謝謝你指出pythonic的方式。 –

0

只是保持團隊智慧分數的字典。

sum = {} 

for line in table: 
    teamA,teamB,scoreA,scoreB = line.split(':') 
    if teamA in sum.keys(): 
     sum[teamA] += scoreA 
    else: 
     sum[teamA] = scoreA 

    if teamB in sum.keys(): 
     sum[teamB] += scoreB 
    else: 
     sum[teamB] = scoreB