gpt4 book ai didi

python - 从文本文件计算

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:20 27 4
gpt4 key购买 nike

我有一个文本文件包含:

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 对阵 SSG 在第一场比赛中得分 1,这使得 SKT 成为赢家。因此,count + 1

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

最佳答案

您可以创建一个字典来存储所有团队的获胜分数。

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

关于python - 从文本文件计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43452802/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com