Skip to main content
 首页 » 编程设计

python之在我的 'high scores' python 程序中,比较运算符引发错误,但只是有时

2025年05月04日7luoye11

问题是指下面的python程序——

# High Scores 
# Maintains a list of the five highest scores and the players responsible. 
 
hiscores = [56,45,23,11] 
again = "a" 
 
 
def findplace(xlist, x): 
    # list is in descending order 
    for j in range(len(xlist)-1): 
        if x >= xlist[j]: 
            xlist.insert(j, x) 
            return xlist 
 
 
while again: 
    print("\n", hiscores) 
    score = int(input("\nEnter a score (zero to exit): ")) 
    if score >= hiscores[3]: 
        hiscores = findplace(hiscores, score) 
    elif score == 0: 
        again = "" 
 
 
print(hiscores) 
input("\nETE") 

该程序从用户那里获取分数,如果分数足够高,则将其添加到列表中。我想通过将 while 循环第三行的索引值设置为 3 来将入门级别设置为最低分,但这会引发错误。 0、1 和 2 完美地工作!我做错了什么?

请您参考如下方法:

我无法用“入门级”分数重现您的问题。但是,由于您的列表无论如何都只有五个元素,因此您可以通过完全放弃入口级别检查来简化事情。

while True: 
    print("\n", hiscores) 
    score = int(input("\nEnter a score (zero to exit): ")) 
    if score == 0: 
        break 
    hiscores = findplace(hiscores, score) 

另请注意,您的 findplace 方法会将高分列表扩展到超过五个条目,如果分数不在第一个 中,它会返回 None code>len-1 条目。相反,您可以只添加新分数,以相反的顺序对列表进行排序,然后取前五个元素。

def findplace(xlist, x): 
    return sorted(xlist + [x], reverse=True)[:5]