scores = []
surfers = []
results_f = open("results.txt")
for each_line in results_f:
(name,score) = each_line.split()
scores.append(float(score))
for line in results_f:
(name,score) = line.split()
surfers.append(name)
results_f.close()
scores.sort(reverse = True)
print("The high scores are : ")
print("1 - "+str(scores[0]))
print("2 - "+str(scores[1]))
print("3 - "+str(scores[2]))
print(surfers[0])
只是一个实验计划。但第二个for循环似乎没有运行。如果我切换for循环的位置;再次,第二个位置的循环不会运行。为什么会这样?
答案 0 :(得分:7)
文件不是列表。如果不重新读取文件对象,则无法循环它们,因为文件位置在读完后不会重置为开头。
您可以在循环之间添加results_f.seek(0)
:
for each_line in results_f:
(name,score) = each_line.split()
scores.append(float(score))
results_f.seek(0)
for line in results_f:
(name,score) = line.split()
surfers.append(name)
但是,如果不循环两次,你会更好地 。您已在第一个循环中获得name
信息。只需循环一次:
for each_line in results_f:
(name,score) = each_line.split()
scores.append(float(score))
surfers.append(name)
您的代码只对scores
列表进行排序; surfers
列表不会效仿。如果您需要对名称和分数进行排序,请将您的姓名和分数放在一个列表中;如果你把分数放在首位,你甚至不需要告诉sort
任何特别的东西:
surfer_scores = []
for each_line in results_f:
name, score = each_line.split()
surfer_scores.append((float(score), name))
surfer_scores.sort(reverse=True)
print("The high scores are : ")
for i, (score, name) in enumerate(surfer_scores[:3], 1):
print("{} - {}: {}".format(i, name, score)