I'm currently working on a challenge that requires me to save high scores to a .txt file. I'm happy with the process of writing the scores to the file, but I'm having some real difficulty working out how to order it in descending order.
我目前正在開展一項挑戰,要求我將高分保存到.txt文件中。我對將分數寫入文件的過程感到滿意,但我正在努力解決如何按降序排序的問題。
I understand that I'm only able to write strings and not integers to a text file, but this leads to me not being able to order the scores as I would like, for example, .sort(reverse=True) would place a 9 higher than 15 on the list.
我知道我只能將字符串而不是整數寫入文本文件,但這導致我無法按照我的意願訂購分數,例如,.sort(reverse = True)會放置9列表中高於15。
Is there any way around this issue at all or is this just the nature of writing to a .txt file? Thanks in advance and here is my code:
有什么方法可以解決這個問題,還是僅僅是寫入.txt文件的本質?在此先感謝,這是我的代碼:
def high_score():
# open high scores
try:
text_file = open("high_score.txt", "r")
high_scores = text_file.readlines()
except FileNotFoundError:
high_scores = []
# get a new high score
name = input("What is your name? ")
player_score = input("What is your score? ")
entry = (player_score + " - " + name + "\n")
high_scores.append(entry)
high_scores.sort(reverse=True)
high_scores = high_scores[:5]
# write high scores to .txt file
text_file = open("high_score.txt", "w+")
for line in high_scores:
text_file.write(line)
2 个解决方案
#1
0
The correct way is to first store a list of pairs (2-tuples) containing each a numerical score and a name, then sort the list by the numerical scores (descending order) and only then convert each pair record to a string and write that to the file.
正確的方法是首先存儲包含每個數字分數和名稱的對(2元組)列表,然后按數字分數(降序)對列表進行排序,然后將每對記錄轉換為字符串並寫入到文件。
You code could become:
你的代碼可能變成:
def high_score():
# open high score file
try:
linenum = 0
with open("high_score.txt", "r") as text_file: # ensure proper close
high_scores = []
for line in text_file:
linenum += 1
score, name = line.strip().split('-', 1)
high_scores.append((int(score), name))
except FileNotFoundError:
high_scores = []
except ValueError:
print("Error line", linenum)
# get a new high score
name = input("What is your name? ")
player_score = input("What is your score? ")
high_scores.append((int(player_score), name))
high_scores.sort(reverse=True, key=lambda x: x[0])
high_scores = high_scores[:5]
# write high scores to .txt file
with open("high_score.txt", "w+") as high_scores
for line in high_scores:
text_file.write(str(line[0] + "-" + line[1])
#2
0
您需要的是自然訂單排序...請參閱:https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
You can simplify the code from the blog to suit your need...
您可以簡化博客中的代碼以滿足您的需求......
get_sort_keys = lambda k: int(k.split(' ')[0])
high_scores.sort(key=get_sort_keys, reverse=True)