2

質問は、次の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 行目の index 値を 3 に設定して、エントリ レベルを最低スコアに設定したかったのですが、これではエラーが発生します。0、1、2 は完全に機能します。私は何を間違っていますか?

4

2 に答える 2

0

問題はfindplace、スコアが高スコアの場合にのみ新しいリストを返すことです。11挿入されていないを入力すると、returnステートメントにヒットしません (したがって、 が返されますNone)。を設定したのでhighscores = findplace(hiscores, score)、基本的にリストを に設定しNoneTypeError.

ループ インreturn xlistと同じレベルに移動すると、このエラーが修正されます (ただし、関数の論理エラーが明らかになります。これについては、後で説明します)。forfindplacefindplace

于 2013-03-14T15:22:07.293 に答える
0

「初心者レベル」のスコアの問題を再現できません。ただし、リストには要素が 5 つしかないため、エントリ レベルのチェックを完全に削除することで作業を簡単にすることができます。

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

findplaceまた、このメソッドはハイ スコア リストを 5 つ以上のエントリに拡張しNone、スコアが最初のエントリ内にない場合に返される可能性があることにも注意してくださいlen-1。代わりに、新しいスコアを追加し、リストを逆順に並べ替えて、最初の 5 つの要素を取得するだけで済みます。

def findplace(xlist, x):
    return sorted(xlist + [x], reverse=True)[:5]
于 2013-03-14T14:20:05.020 に答える