在我的';高分';在python程序中,比较运算符会引发错误,但这只是偶尔发生的
问题涉及以下python程序-在我的';高分';在python程序中,比较运算符会引发错误,但这只是偶尔发生的,python,python-3.x,Python,Python 3.x,问题涉及以下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
# 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
方法会将高分列表扩展到五个以上的条目,如果分数不在第一个len-1
条目内,它可以返回None
。相反,您可以只添加新的分数,按相反的顺序对列表排序,然后获取前五个元素
def findplace(xlist, x):
return sorted(xlist + [x], reverse=True)[:5]
问题在于
findplace
仅在分数较高时返回新列表。如果输入未插入的11
,它不会命中return
语句(因此返回None
)。由于您设置了highscores=findplace(hiscores,score)
,因此实际上您将列表设置为None
,从而导致类型错误
将return xlist
移动到与findplace
中的for
循环相同的级别可以修复此错误(但会在findplace
函数中显示一个逻辑错误,我将留给您去发现)。它会引发什么错误?我要注意,这里没有截断或以其他方式控制分数列表的长度,因此,这将存储5个以上的分数,只要它们在插入时都高于列表中的第4个分数…如果添加11或更高的分数,则下一行的输出为无。任何进一步的值都会在引用相关行时引发“TypeError:“NoneType”对象不可下标”。但如果值低于3,则不会发生这种情况。另外,我知道列表没有限制,程序还没有完成。谢谢大家,findplace没有命中return语句,因为For循环中有-1。范围自动变为小于长度的一个,不必显式编码。没有人是线索。