Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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])

Just an experimental program. But the second for loop doesn't seem to run. If I switch the positions of the for loops; again the loop in the second position wouldn't run. Why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
384 views
Welcome To Ask or Share your Answers For Others

1 Answer

Files are not lists. You can't loop over them without rewinding the file object, as the file position doesn't reset to the start when you finished reading.

You could add results_f.seek(0) between the loops:

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)

but you'd be much better off by not looping twice. You already have the name information in the first loop. Just loop once:

for each_line in results_f:
    (name,score) = each_line.split()
    scores.append(float(score))
    surfers.append(name)

Your code only sorts the scores list; the surfers list will not follow suit. If you need to sort names and scores together, put your names and scores together in a list; if you put the score first you don't even need to tell sort anything special:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...