从文本文件计算

时间:2017-04-17 13:48:39

标签: python

我有一个包含以下内容的文本文件:

SKT:SSG:2:1
NJW:UIA:1:0
SKT:TRP:3:2
SSG:NJW:0:2

我想计算每个团队对应于文本文件中的数字的获胜次数。例如:

SKT: 2
NJW: 2
UIA: 0
SSG: 0

这是我到目前为止所拥有的:

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

for line in match:
    contents = line.strip().split(':')
    table.append(contents)
dictionary = {}
for line in table:
    #how do i code the index of the team and it's score?
    .
    .

只是片刻来测试我的理解,如果我要计算每个团队获胜的次数,我必须确保python能够读取,例如, SKT 得分 2 对抗游戏1中 SSG 得分 1 ,这使 SKT成为赢家。因此,计数+ 1

但是,我对如何将团队名称的索引与其得分相对应感到困惑。任何帮助表示赞赏。问候。

3 个答案:

答案 0 :(得分:1)

你可以创建一个dict来存储所有团队获胜分数。

res = {}
for line in match:
   team1,team2,score1,score2 = line.split(':')
   if team1 not in res: res[team1] = 0
   if team2 not in res: res[team2] = 0
   if int(score1) == int(score2):
      continue 
   else:
      winner = team1 if int(score1) > int(score2) else team2
      res[winner] += 1

答案 1 :(得分:1)

你可以使用字典。

fileName = input("Enter the file name:")
match = open(fileName)

d = {}
for line in match:
    x, y, sx, sy = line.split(":")

    if not x in d:
        d[x] = 0
    if not y in d:
        d[y] = 0
    if sx > sy:
        d[x] += 1
    elif sx < sy:
        d[y] += 1


print(d)

结果:

{'SKT': 2, 'SSG': 0, 'NJW': 2, 'UIA': 0, 'TRP': 0}

答案 2 :(得分:1)

使用collections.defaultdict简化了程序:

import collections

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)