基于指数的计算

2024-06-01 14:38:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件包含:

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代码,以确保同一团队的索引与文本文件的另一部分中显示的数字的索引相对应,从而获得总和。当做。你知道吗


Tags: 代码informatchlinecontentstablefilename
3条回答

只需维护一个团队智慧分数字典。你知道吗

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

试试这个:

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

您可以使用^{}执行此操作

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)

相关问题 更多 >