我有一个名为 score.txt 的文本文件,内容为:
dave 100
ben 50
mary 5
hello 75
elwin 360
didier 1000
ken 85
jibril 79
heyo 900
alan 23
wy 57
sam 99
我正在使用以下代码:
with open ("score.txt") as f:
for line in reversed(sorted([line.rstrip().split() for line in f],key=lambda x : int(x[1]) )):
d=("\t".join(line))
print(d)
with open("scoreboard_sorted.txt","a") as file:
file = file.write(d+"\n")
with open("scoreboard_sorted.txt") as myfile:
output=myfile.readlines()[0:10]
print(output)
结果在 scoreboard_sorted.txt 中是这样的:
didier 1000
heyo 900
elwin 360
dave 100
sam 99
ken 85
jibril 79
hello 75
wy 57
ben 50
alan 23
mary 5
,并输入代码:
with open("scoreboard_sorted.txt") as myfile:
output=myfile.readlines()[0:10]
print(output)
结果是:
['didier\t1000\n', 'heyo\t900\n', 'elwin\t360\n', 'dave\t100\n', 'sam\t99\n', 'ken\t85\n', 'jibril\t79\n', 'hello\t75\n', 'wy\t57\n', 'ben\t50\n']
好,所以问题是我希望它像这样打印:
1. didier 1000
2. heyo 900
3. elwin 360
4. dave 100
5. sam 99
6. ken 85
7. jibril 79
8. hello 75
9. wy 57
10.ben 50
我应该在里面添加一个计数器吗?
答案 0 :(得分:0)
假设内容在文件“ txt”中,则以下代码应在python
中起作用。 (尽管它不会保留空格)
with open ("txt") as f:
for line in sorted(
[line.rstrip().split() for line in f],
key=lambda x : int(x[1])
):
print(" ".join(line))
简单来说,您可以在cmdline中执行以下操作,同时保留空白
sort -k 2 -g txt