如何将字符串和整数添加到文件中然后进行排序?

时间:2019-10-23 22:16:37

标签: python python-3.x

在我的代码中,程序要求输入用户名和分数。但是,我可以将分数发送到文件并进行排序。有什么方法可以更改代码,以便将播放器名称发送到文件,并与相应的编号一起排序。

player_1=input('What is your name?')
points1=input('What is your score?')
player_2=input('What is your name?')
points2=input('What is your score?')

leaderboard=input('Type YES if you would like to see the tp scores and NO if you wouldnt')
while leaderboard=='YES':
    Scorefile=open('scores.txt','a')
    Scorefile.write(points1)
    Scorefile.write("\n")
    Scorefile.write(points2)
    Scorefile.write("\n")
    Scorefile.close()
    Scorefile = open('scores.txt','r')
    with open('scores.txt','r') as Scorefile:
        scores=Scorefile.readline()
        List1=[]
        while scores:
            scores2=(scores.strip())
            List1.append(scores2)
            scores=Scorefile.readline()
    for i in range(0, len(List1)):
        List1[i] = int(List1[i])        
    List1.sort(reverse=True)

    print(List1[0:5])
    leaderboard='ANYTHING'
while leaderboard=='NO':
    sys.exit()

1 个答案:

答案 0 :(得分:0)

为什么不创建2个文件并具有第1个文件存储字符串和第2个文件存储int。 然后从两个位置提取信息。非常简单容易。