[英]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.