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

您想要的可能是通常所说的“自然排序”。搜索“natural sort python”会得到很多结果,但在ASPN上有一些很好的讨论。

于 2009-10-16T05:49:38.820 回答
0

对你的做一个简单的字符串排序

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

items 不起作用,因为例如 str(1000) < str(500)。换句话说,在字母数字排序中,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 将其附加到单词列表(您可以在此处使用更好的名称)并在打印前对其进行反向排序。或者你可以使用 bisect.insort 库函数而不是 list.append。

此外,比 Pythonic 形式更

if file_exists == False:

是:

if not file_exists:
于 2009-10-16T04:57:44.267 回答
0

我想当你粘贴 Alex 的答案时出了点问题,所以这是你的代码,里面有一个排序


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 回答