简体   繁体   English

Python:第二个for循环没有运行

[英]Python : The second for loop is not running

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. 但第二个for循环似乎没有运行。 If I switch the positions of the for loops; 如果我切换for循环的位置; 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. 如果不重新读取文件对象,则无法循环它们,因为文件位置在读完后不会重置为开头。

You could add results_f.seek(0) between the loops: 您可以在循环之间添加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)

but you'd be much better off by not looping twice. 但你会通过不循环两次好得多 You already have the name information in the first loop. 您已在第一个循环中拥有name信息。 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; 您的代码只对scores列表进行排序; the surfers list will not follow suit. surfers名单不会效仿。 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: 如果你第一次把比分你甚至都不需要告诉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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM