gpt4 book ai didi

python - 如何按2个整数排序

转载 作者:行者123 更新时间:2023-12-01 06:57:14 25 4
gpt4 key购买 nike

我尝试了很多选项来尝试正确排序,但没有成功。使用这段代码意味着将完全排序的列表输出到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com