* python代码*问题/ s与.txt文件和元组+字典
问题描述:
我正在写这个游戏,并无法编码我的高分列表。* python代码*问题/ s与.txt文件和元组+字典
高分表由一个.txt文件组成,其中名称,分数按该顺序列出,现在每个新行都有一个新行,用于测试它。
Matthew, 13
Luke, 6
John, 3
我的代码来记录比分是:
print "You got it!\nWell done", NAME,",You guessed it in", count, "guesses."
save = raw_input("\nWould you like to save your score? (Y)es or (N)o: ")
save = save.upper()
if save == "Y":
inFile = open("scores.txt", 'a')
inFile.write("\n" + NAME + ", " + str(count))
inFile.close()
count = -1
if save == "N":
count = -1
和我的代码来显示比分是:
def showScores():
inFile = open("scores.txt", 'r')
scorelist = {}
for line in inFile:
line = line.strip()
parts = [p.strip() for p in line.split(",")]
scorelist[parts[0]] = (parts[1])
players = scorelist.keys()
players.sort()
print "High Scores:"
for person in players:
print person, scorelist[person]
inFile.close()
我不知道如何正确排序,右现在按照字母顺序排序,但我想按从小到大的顺序排序,但仍保留NAME的格式。
而且每一次,我尝试保存新高得分与它存储在同一名称...
为.txtMatthew, 13
Luke, 6
John, 3
Mark, 8
Mark, 1
,但只显示同最近的得分名,
在Python Shell
High Scores:
John 3
Luke 6
Mark 1
Matthew 13
或者只显示了相同的一个实例它时间,我想..有没有人知道如何解决这个问题呢?
在此先感谢
答
要解决这两个排序和多分数的单一名称,你可能想改变你的数据结构。以下是我会写的代码显示:
def showScores():
inFile = open("scores.txt", 'r')
scorelist = []
for line in inFile:
line = line.strip()
score = [p.strip() for p in line.split(",")]
score[1] = int(score[1])
scorelist.append(tuple(score))
scorelist.sort(key=lambda x: x[1])
print "High Scores:"
for score in scorelist:
print score[0], score[1]
inFile.close()
这使用元组,而不是一本字典,其中元组包含两个元素的列表:玩家的名字,随后比分。
一个额外的注意事项:您需要确保NAME不包含逗号或换行符以避免损坏分数文件。
答
要通过分数,而不是按名称排序,使用key
关键字参数。
players.sort(key=lambda x: int(scorelist[x]))
要回答你的第二个问题(我认为?),你正在使用字典来保存分数。所以任何名字一次只能存储一个分数。
parts = [p.strip() for p in line.split(",")]
scorelist[parts[0]] = (parts[1]) #second Mark score overwrites first Mark score
如果要存储多个分数,请存储分数列表而不是单个int。 (另外,如果你用你的拆包代码将更具可读性。)
name, score = [p.strip() for p in line.split(",")]
if name not in scorelist:
scorelist[name] = []
scorelist[name].append(score)
当然,如果你这样做,按分数排序变得更加复杂。既然你要由同一个人存储多个分数,你会更好节约元组的列表
def showScores():
inFile = open("scores.txt", 'r')
scorelist = []
for line in inFile:
line = line.strip()
namescore = tuple(p.strip() for p in line.split(","))
scorelist.append(namescore)
scorelist.sort(key=lambda namescore: int(namescore[1]))
print "High Scores:"
for name, score in scorelist:
print name, score
inFile.close()
+1,关于转换为“int”和关于名称的观点。 – senderle 2011-04-29 04:57:25
感谢您的额外建议,:) – Jerry 2011-04-29 05:41:58