0

私はあなたのスコアをhighscores.txtファイルに保存する愚かな小さなゲームを作っています。

私の問題は行の並べ替えです。これが私がこれまでに持っているものです。

たぶん、Python用の英数字ソーターが役立つでしょうか?ありがとう。

import os.path
import string

def main():
    #Check if the file exists
    file_exists = os.path.exists("highscores.txt")

    score = 500
    name = "Nicholas"

    #If the file doesn't exist, create one with the high scores format.
    if file_exists == False:
        f = open("highscores.txt", "w")
        f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')

    new_score = str(score) + ".........." + name

    f = open("highscores.txt", "r+")
    words = f.readlines()
    print words

main()
4

5 に答える 5

4

words = f.readlines()、次のようなことを試してください。

headers = words.pop(0)

def myway(aline):
  i = 0
  while aline[i].isdigit():
    i += 1
  score = int(aline[:i])
  return score

words.sort(key=myway, reverse=True)

words.insert(0, headers)

キー(;-)のアイデアは、各アイテム(ここでは行)から「ソートキー」を返す関数を作成することです。私は可能な限り簡単な方法でそれを書き込もうとしています。先頭の桁がいくつあるかを確認し、それらをすべてintに変換して、それを返します。

于 2009-10-16T01:12:40.867 に答える
1

ハイスコ​​アをより堅牢な形式で保存することをお勧めします。特にJSONをお勧めします。

import simplejson as json  # Python 2.x
# import json  # Python 3.x

d = {}
d["version"] = 1
d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]]
s = json.dumps(d)
print s
# prints:
# {"version": 1, "highscores": [[100, "Steve"], [200, "Ken"], [400, "Denise"]]}


d2 = json.loads(s)
for score, name in sorted(d2["highscores"], reverse=True):
    print "%5d\t%s" % (score, name)

# prints:
#  400  Denise
#  200  Ken
#  100  Steve

JSON を使用すると、ハイスコア テーブルなどの保存済みファイルからデータを復元するために独自のパーサーを作成する必要がなくなります。すべてを辞書に入れるだけで、簡単に元に戻すことができます。

ハイスコ​​アの保存形式のバージョン番号であるバージョン番号を挿入したことに注意してください。データの保存形式を変更したことがある場合、そこにバージョン番号があると非常に便利です。

于 2009-10-16T05:26:06.877 に答える
0

あなたが欲しいのは、おそらく一般的に「自然順」として知られているものです。「自然順python」を検索すると多くの結果が得られますが、ASPNについてはいくつかの良い議論があります。

于 2009-10-16T05:49:38.820 に答える
0

あなたの単純な文字列ソートを行う

new_score = str(score) + ".........." + name

たとえば、str(1000) < str(500) であるため、items は機能しません。つまり、英数字ソートでは 1000 が 500 より前になります。

アレックスの答えは、ソートキー機能の使用を示しているという点で優れていますが、もう少し単純で、ハイスコア表示を視覚的に整列させるという利点がある別のソリューションを次に示します。

あなたがする必要があるのは、スコアの最大サイズの固定フィールドで数字を右揃えにすることです (最大 5 桁で ver < 3.0 と仮定):

new_score = "%5d........%s" % (score, name)

または Python バージョン 3.x の場合:

new_score = "{0:5d}........{1}".format(score, name)

各 new_score について、それを単語リストに追加し (ここではより適切な名前を使用できます)、印刷する前に逆順に並べ替えます。または、list.append を実行する代わりに、bisect.insort ライブラリ関数を使用することもできます。

また、より Pythonic なフォーム

if file_exists == False:

は:

if not file_exists:
于 2009-10-16T04:57:44.267 に答える
0

アレックスの回答から貼り付けたときに何か問題が発生したと思いますので、並べ替えを含むコードを次に示します


import os.path

def main():
    #Check if the file exists
    file_exists = os.path.exists("highscores.txt")

    score = 500
    name = "Nicholas"

    #If the file doesn't exist, create one with the high scores format.
    if file_exists == False:
        f = open("highscores.txt", "w")
        f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')

    new_score = str(score) + ".........." + name +"\n"

    f = open("highscores.txt", "r+")
    words = f.readlines()

    headers = words.pop(0)

    def anotherway(aline):
      score="" 
      for c in aline:
          if c.isdigit():
              score+=c
          else:
              break
      return int(score)

    words.append(new_score)
    words.sort(key=anotherway, reverse=True)

    words.insert(0, headers)

    print "".join(words)

main()
于 2009-10-16T05:19:03.593 に答える