gpt4 book ai didi

Python-如何对文件中的值求和

转载 作者:太空宇宙 更新时间:2023-11-03 15:32:26 29 4
gpt4 key购买 nike

所以我有一个文件。其中有 3 行,每行告诉 Name;sport:points

Kevin;Football:604,196,47;Golf:349,0,0;Tennis:797,426,124
Julia;Football:350,254,1;Golf:242,58,38
Bob;Football:260,18,0

我有代码,但我不知道如何计算每项运动的分数

f=open("points.txt", "r")
s=f.readlines()
p=str(s)

for line in s:
printnum=0
printnum+=float(line)



for line in s:
if p.isdigit():
total=0
for number in s:
total+=int(number)
print(total)

所以结果应该是这样的

Alvin:
- Football: 278
Kevin:
- Football: 847
- Golf: 349
- Tennis: 1347
Sam:
- Football: 605
- Golf: 338

所以基本上我不知道热求和键值

最佳答案

from ast import literal_eval as leval

my_dict = {}
for line in s:
name, *sports = line.split(';')
my_dict[name] = {sport.split(':')[0]: sum(leval(sport.split(':')[1])) for sport in sports}

for player in my_dict:
print('{}:'.format(player))
for sport in my_dict[player]:
print(' - {}: {}'.format(sport, my_dict[player][sport]))

# Produces:
# Kevin:
# - Golf: 349
# - Tennis: 1347
# - Football: 847
# Julia:
# - Golf: 338
# - Football: 605
# Bob:
# - Football: 278

关于Python-如何对文件中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811478/

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