所以我有一个文件。 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 - Python-如何对文件中的值求和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42811478/