*python代码* 处理.txt文件与元组和字典的问题

2 投票
2 回答
1414 浏览
提问于 2025-04-16 16:38

我正在写一个游戏,但在编写我的高分榜时遇到了麻烦。

高分榜是一个.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()

我不知道怎么正确排序,现在它是按字母顺序排序的,但我想按数字从小到大排序,同时保持格式为名字和分数。

另外,每次我尝试用相同的名字保存一个新的高分时,它会存储在...

.txt文件中

Matthew, 13
Luke, 6
John, 3
Mark, 8
Mark, 1

但只显示同一个名字的最新分数,

在python命令行中

High Scores:
John 3
Luke 6
Mark 1
Matthew 13

或者只显示同一个项目的一次,我想知道有没有人知道怎么解决这个问题?

提前谢谢大家!

2 个回答

3

如果你想按分数排序,而不是按名字排序,可以使用 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

如果你想存多个分数,那就要存一个分数的列表,而不是一个单独的整数。(另外,如果你使用解包,代码会更容易读。)

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

为了同时解决排序和一个名字对应多个分数的问题,你可能需要改变一下你的数据结构。下面是我写的显示代码:

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

这里使用的是一个元组的列表,而不是字典。每个元组包含两个部分:一个是玩家的名字,另一个是分数。

还有一点需要注意:你要确保名字中不包含逗号或换行符,这样可以避免损坏分数文件。

撰写回答