排序.txt文件行不按预期工作

时间:2019-06-05 08:38:23

标签: python sorting

所以问题是当我执行排行榜代码时,它输出: 某些排行榜正确,但随后添加了错误的行。

我尝试删除txt文件中的内容,但这没用。

def save():
    global totalone,totaltwo,name1,name2,rounds
    file=open("scores.txt","a")
    if totalone < totaltwo:
        #name2 V name1 | totaltwo
        file.write(f"Scored {totaltwo} | Winner:{name2} V {name1} | played 0 H2H rounds\r")
    elif totaltwo < totalone:
        #name1 V name2 | totalone
        file.write(f"Scored {totalone} | Winner:{name1} V {name2} | Played 0 H2H rounds\r")
    else:
        #name1 V name2 | Tied | rounds
        if totalone < totaltwo:
            file.write(f"Scored {totalone} | Winner:{name1} V {name2} | Tied | Played {rounds} H2H rounds\r")
        elif totaltwo < totalone:
            file.write(f"Scored {totaltwo} | Winner:{name2} V {name1} | Tied | Played {rounds} H2H rounds\r")

    file.close()
def leaderboard():
    file=open("scores.txt","r")
    data=file.readlines()
    data.sort(reverse=True)
    x = 0
    for i in range(len(data)):
        print((data[i].strip()))
        x += 1
        if x == 5:
            break
    file.close()

预期结果是:

Scored 70 | Winner:Mark V Athy | Played 0 H2H rounds
Scored 45 | Winner:Athy V Mark | played 0 H2H rounds
Scored 40 | Winner:Mark V Athy | Played 0 H2H rounds
Scored 35 | Winner:Athy V Mark | played 0 H2H rounds
Scored 5 | Winner:Mark V Athy | Played 0 H2H rounds

但它输出:

Scored 70 | Winner:Mark V Athy | Played 0 H2H rounds
Scored 5 | Winner:Mark V Athy | Played 0 H2H rounds
Scored 45 | Winner:Athy V Mark | played 0 H2H rounds
Scored 40 | Winner:Mark V Athy | Played 0 H2H rounds
Scored 35 | Winner:Athy V Mark | played 0 H2H rounds

2 个答案:

答案 0 :(得分:1)

data=file.readlines()
data.sort(reverse=True)

这将按字母顺序对行进行排序,因此

Scored 7…
Scored 5…
Scored 4…

是“正确”。

在格式化输出行之前,您需要根据数字分数(totalonetotaltwo变量)进行排序。

答案 1 :(得分:0)

有关真正正确的解决方案,请参阅@ mkrieger1的解决方案(在格式化之前根据具体值进行实际排序)。

要获得一种快速且肮脏的解决方案,只需将data.sort(...)替换为:

data.sort(reverse=True, key=lambda line: int(line.split()[1]))

这是告诉排序使用第一和第二个空格之间的值(恰好是分数),并将其强制转换为整数(因此排序是数字而不是字母顺序的)

说明:

这是非常糟糕的做法,因为如果更改行格式,它可能会中断(这与排行榜的排序方式无关,仅与显示有关)。

因此,就软件工程而言,这并不是一个好习惯。很快就可以了。