Python:第二个 for 循环未运行 [英] Python : The second for loop is not running

查看:85
本文介绍了Python:第二个 for 循环未运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 循环的位置;再次,第二个位置的循环不会运行.为什么会发生这种情况?

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?

推荐答案

文件不是列表.你不能在不回绕文件对象的情况下循环它们,因为当你完成阅读时文件位置不会重置到开头.

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.

您可以在循环之间添加 results_f.seek(0):

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)

但是如果不循环两次,你会好得多.您已经在第一个循环中获得了 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)

您的代码只对scores 列表进行排序;surfers 列表不会效仿.如果您需要将姓名和分数一起排序,请将您的姓名和分数放在一个列表中;如果你把分数放在第一位,你甚至不需要告诉 sort 任何特别的东西:

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)

这篇关于Python:第二个 for 循环未运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆