2
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?

0

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, just was wondering about the second for loop not working for which you already answered.
Thank you for the additional info, very helpful.
Still surprised. How could two data items be put in a single spot in a list?
@Vasanth: The magic of nested structures! There is one object in that spot, a tuple. The tuples, in turn, each contain two elements (a score and a name).
@Vasanth: see What does enumerate mean?, the surfer_scores[:3] expression takes the first 3 elements (so the 3 highest scores), and enumerate() adds a number to each element, starting at 1 (the second argument to enumerate()). So the loop gives you 3 numbered score - name pairs.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.