繁体   English   中英

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

[英]Sorting strings with integers and text in Python

我正在做一个愚蠢的小游戏,将您的分数保存在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()

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并返回。

我想鼓励您以更可靠的格式存储您的高分。 我特别建议使用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将使您不必编写自己的解析器即可从保存的文件(例如高分表)中恢复数据。 您可以将所有内容都塞进字典,然后将其全部收回。

请注意,我填写了一个版本号,即您的高分保存格式的版本号。 如果您曾经更改过数据的保存格式,那么拥有版本号将是一件非常好的事情。

对您的字符串进行简单的排序

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

这些项目将无法正常工作,例如str(1000)<str(500)。 换句话说,在字母数字排序中,1000会排在500之前。

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

您需要做的是将您的数字正确地排列在最大分数的固定字段中,这样(假设最大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:

我猜您从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()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM