2017-04-18 40 views
0

我有一張表格代表遊戲結果。從表格中獲取元素並統計總數

GameTab = [['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']] 

我追加的結果從一個文本文件導入表的形式所以這裏的文本格式:說得容易,它的解釋中,使得例如,TRE打進1和ARD打進1 PRK拿下2和GEA 3分。

TRE:ARD:1:1 
PRK:GEA:2:3 
ARD:PRK:1:0 
TRE:GEA:2:1 

而是獲得結果的球員,我想獲得對手的結果來代替。我以一種獲得球員結果的方式完成了我的代碼,但我想不出一種方法來獲得對手的結果。

例如,在比賽中PRK的:GEA和TRE:GEA:

The opponent of GEA scored a total of: 4 

我的代碼:

gameTab =[['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'], 
      ['TRE','GEA','2','1']] 

dictionary = {} 
for i in gameTab: 
    for c in range(len(i[:2])): 
     if i[:2][c] not in dictionary.keys(): 
       dictionary[i[:2][c]] = int(i[2:][c]) 
     else: 
      dictionary[i[:2][c]] += int(i[2:][c]) 
print(dictionary) 
+0

您是否嘗試過使用熊貓數據框? (http://pandas.pydata.org/pandas-docs/stable/dsintro.html#)它允許非常簡單地格式化這些表格。 (參見http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) – Chris

回答

0

爲了獲得對手的結果,對一個隊,下面的代碼滿足以下條件:

gameTab =[['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']] 

dictionary = {} 
for i in gameTab: 
    if i[0] in dictionary: 
    dictionary[i[0]] += int(i[3]) 
    else: 
    dictionary[i[0]] = int(i[2]) 

    if i[1] in dictionary: 
    dictionary[i[1]] += int(i[2]) 
    else: 
    dictionary[i[1]] = int(i[2]) 

print(dictionary) 

它打印出:{'ARD': 1, 'GEA': 4, 'TRE': 2, 'PRK': 3}

基本上遍歷列表,併爲每個團隊檢查它是否存在於字典中,然後將其值作爲對手值增加。最後你會得到反對派對陣一支球隊的全部得分。

0
gametab = [['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']] 

dicta = {} 
for i in range(len(gametab)): 
    for j in range(2): 
     if gametab[i][j] in dicta: 
      dicta[gametab[i][j]] += int(gametab[i][j+2]) 
     else: 
      dicta[gametab[i][j]] = int(gametab[i][j+2]) 

print dicta