这是一个缩进错误。你要低于这个区块是第一缩进级别:
for name in sorted(user_scores):
# get the highest score in the list
average = sum(user_scores[name]) /float(len(user_scores[name]))
print(name, "'s average from the last 3 scores is", average)
另外,还有一些在您的代码是写在一个糟糕的方式很多地方。这里有一个优化:
user_scores = {}
# 'with' will automatically closes the file after leaving its code block:
with open("Class1.txt") as scorefile:
for line in reversed(scorefile.readlines()):
name, score = line.split()
# nested if inside if/else is better than if-and plus if not:
if name in user_scores:
if len(user_scores[name]) < 3:
user_scores[name].append(int(score))
else:
user_scores[name] = [int(score)]
# If you want to sort by the numeric value, replace 'sorted(user_scores)' with
# 'sorted(user_scores, key=lambda k: user_scores[k])':
for name in sorted(user_scores):
# in Python 3 the '/' operator always returns the appropriate format.
# to get a pure integer division without decimal places, you would use '//'.
# Therefore no need for the float(...) conversion.
average = sum(user_scores[name])/len(user_scores[name])
# str.format(...) is more flexible than just printing multiple items:
print("{}'s average from the last 3 scores is {}".format(name, average))
# No need to store another dictionary with best scores.
# If you want to sort by the numeric value, replace 'sorted(user_scores)' with
# 'sorted(user_scores, key=lambda k: user_scores[k])':
for name in sorted(user_scores):
print("{}'s best score is {}".format(name, max(user_scores[name])))
使用树方法来创建数据。可以使用'ast.literal_eval(line.strip())' – dsgdfg
谢谢有更简单的方法吗? – Canadian1010101
是否希望输出按名称或数字值(最高分/平均值)按字母顺序排序? –