单步操作
将所有数据读入字典中:
data = {}
for line in f:
name, value = line.split('=')
name = name.strip()
value = int(value)
data.setdefault(name, []).append(value)
< p >
data
的内容:
{'Chris': [9, 9],
'John': [6, 4, 5],
'Sarah': [4, 7],
'Tanzil': [4, 4, 10, 5, 3],
'Tom': [2]}
现在您可以计算平均值:
last_scores = data['Tanzil'][-3:]
avg = sum(last_scores) / len(last_scores)
>>> avg
6.0
或者对所有人求平均值:
avg = {}
for name, scores in data.items():
last_scores = scores[-3:]
avg[name] = sum(last_scores) / len(last_scores)
现在avg
的值为:
{'Chris': 9.0, 'John': 5.0, 'Sarah': 5.5, 'Tanzil': 6.0, 'Tom': 2.0}
显示所有结果:
for name, value in avg.items():
print(name, value)
打印:
Tanzil 6.0
Chris 9.0
Sarah 5.5
John 5.0
Tom 2.0
或按平均分从高到低排序:
from operator import itemgetter
for name, value in sorted(avg.items(), key=itemgetter(1), reverse=True):
print(name, value)
打印:
Chris 9.0
Tanzil 6.0
Sarah 5.5
John 5.0
Tom 2.0
完整程序
input_name = input("\nPlease enter students name » ").strip()
datafile = '1.txt'
with open(datafile, 'r') as f:
data = {}
for line in f:
name, value = line.split('=')
name = name.strip()
value = int(value)
data.setdefault(name, []).append(value)
avg = {}
for name, scores in data.items():
last_scores = scores[-3:]
avg[name] = sum(last_scores) / len(last_scores)
print("\n", input_name,"'s average score is", avg[input_name])