我尝试了许多选择来尝试使排序正确而没有成功。
使用这段代码的意思是将一个完全排序的列表输出到winlist.txt上,但是它仅按第一个整数排序,因此无法正确排序。

def sort():
        winfile = list()
        with open ('winners.txt') as fin:
                for line in fin:
                        winfile.append(line.strip('\n'))
        winfile.sort()
        with open('SortWin.txt', 'w+') as fout:
                for winfile in winfile:
                        fout.write(winfile + '\n')


目前,此段代码输出:

11 Tom
2 Tom
20 Ben
20 Tom
21 Ben


但我希望排序以2个整数而不是仅第一个进行排序。
这样2才高于11

最佳答案

尝试使用key参数:

def sort():
    winfile = list()
    with open ('winners.txt') as fin:
            for line in fin:
                    winfile.append(line.strip('\n'))
    winfile.sort(key=lambda x: int(x.split()[0]))
    with open('SortWin.txt', 'w+') as fout:
            for winfile in winfile:
                    fout.write(winfile + '\n')

关于python - 如何按2个整数排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58765878/

10-09 23:22