在 Python 中使用整数和文本对字符串进行排序

发布于 2024-08-08 12:53:01 字数 724 浏览 3 评论 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()

I'm making a stupid little game that saves your score in a highscores.txt file.

My problem is sorting the lines. Here's what I have so far.

Maybe an alphanumeric sorter for python would help? Thanks.

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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

何止钟意 2024-08-15 12:53:01

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,然后返回。

after words = f.readlines(), try something like:

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)

The key (;-) idea is to make a function that returns the "sorting key" from each item (here, a line). I'm trying to write it in the simplest possible way: see how many leading digits there are, then turn them all into an int, and return that.

蓝色星空 2024-08-15 12:53:01

我想鼓励您以更强大的格式存储您的高分。我特别建议 ​​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 将使您不必编写自己的解析器来从保存的文件(例如高分表)中恢复数据。你可以把所有的东西都塞进字典里,然后轻松地把它们全部找回来。

请注意,我塞入了版本号,即您的高分保存格式的版本号。如果您更改了数据的保存格式,其中包含版本号将是一件非常好的事情。

I'd like to encourage you to store your high scores in a more robust format. In particular I suggest 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

Using JSON will keep you from having to write your own parser to recover data from saved files such as high score tables. You can just tuck everything into a dictionary and trivially get it all back.

Note that I tucked in a version number, the version number of your high score save format. If you ever change the save format of your data, having a version number in there will be a very good thing.

允世 2024-08-15 12:53:01

我猜当你粘贴亚历克斯的答案时出了问题,所以这是你的代码,里面有一个排序


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()

I guess something went wrong when you pasted from Alex's answer, so here is your code with a sort in there


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()
我只土不豪 2024-08-15 12:53:01

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

What you want is probably what's generally known as a "Natural Sort". Searching for "natural sort python" gives many results, but there's some good discussion on ASPN.

红衣飘飘貌似仙 2024-08-15 12:53:01

对项目进行简单的字符串排序

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

是行不通的,因为例如 str(1000) <字符串(500)。换句话说,按字母数字排序,1000 将排在 500 之前。

亚历克斯的答案很好,因为它演示了排序键功能的使用,但这里有另一个解决方案,它更简单一些,并且具有视觉上对齐高分显示的附加优势。

您需要做的是将您的数字右对齐在分数最大大小的固定字段中,因此(假设最大 5 位且 ver < 3.0):

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

或者对于 Python ver 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:

Doing a simple string sort on your

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

items isn't going to work since, for example str(1000) < str(500). In other words, 1000 will come before 500 in an alphanumeric sort.

Alex's answer is good in that it demonstrates the use of a sort key function, but here is another solution which is a bit simpler and has the added advantage of visuallaly aligning the high score displays.

What you need to do is right align your numbers in a fixed field of the maximum size of the scores, thus (assuming 5 digits max and ver < 3.0):

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

or for Python ver 3.x:

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

For each new_score append it to the words list (you could use a better name here) and sort it reversed before printing. Or you could use the bisect.insort library function rather than doing a list.append.

Also, a more Pythonic form than

if file_exists == False:

is:

if not file_exists:
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文