有人可以看看我的程序吗?有一个我无法识别的错误,这让我很困惑。另外,请向我解释问题,以便我了解如何在其他情况下使用该功能和程序。
input_name = input("\nPlease enter students name » ").strip()
datafile = '1.txt'
while open(datafile, 'r') as f:
data = {}
for line in f:
name, value = line.split('=')
name = name.strip
value = str(value)
data.setdefault(name, []).append(value)
else:
break
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))
最佳答案
单步
将所有数据读入字典:
data = {}
for line in f:
name, value = line.split('=')
name = name.strip()
value = int(value)
data.setdefault(name, []).append(value)
数据
的内容:
{'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])
关于Python 帮助 |从底部读取文本文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34110140/