我有一个包含以下内容的文本文件:
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
.
.
从我能想到的,我必须编写python以确保同一团队的索引对应于文本文件的其他部分中显示的数字的索引,以便获得总和< / strong>即可。问候。
答案 0 :(得分:1)
discard patt1 | discard patt2 | discard pattN | (capture this)
答案 1 :(得分: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
答案 2 :(得分: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