所以我想从档案中找出最好的两个候选人”数据.txt“然后打印出候选人的名字和分数。最好的候选人是得分最小的人,所以负数很重要。文件如下所示:
最好的两位候选人是金和哈德逊。所以程序应该打印出来:
Kim
40
Hudson
-150
以下是我目前掌握的代码:
name = infile.readline()
score = float(infile.readline())
name2 = infile.readline()
score2 = float(infile.readline())
bestCandidate = name
bestScore = score
bestCandidate2 = name2
bestScore2 = score2
while name != "":
name = infile.readline()
if name != "":
score = float(infile.readline())
if score < bestScore:
bestCandidate = name
bestScore = score
if bestScore < bestScore2:
bestCandidate = name
bestScore2 = score
print(bestCandidate)
print(bestScore)
print(bestCandidate2)
print(bestScore2)
infile.close()
该文件不打印最好的两个,而是打印以下内容:
Hudson
-150
Kim
-150
您可以放置一个
continue
,这样就不会更新bestScore2。continue
语句跳过循环的其余部分,并再次执行while
语句。你知道吗所以输出变成:
下面是使用heapq的更好方法。堆具有维持秩序的特性。这里需要保持分数的顺序,因此在堆中存储(score,name)的元组。所以,如果你两次爆料,你就得到了两个最好的候选人。你知道吗
更好的实现方法是
重要的一点是,如果您找到
x < best
,您需要执行两个操作:second_best = best
和best = x
,以避免丢失应该成为第二个最小值的旧最小值。你知道吗在代码中:
如果您忘记了在
second_best
中移动best
的步骤,程序将无法处理(2,10,1)这样的序列,因为答案将是(1,10)而不是(1,2)。你知道吗相关问题 更多 >
编程相关推荐