如何将行号添加到打印的 table

How to add line numbers to a printed table

我有一个名为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

要不要在里面加个计数器?

假设内容在文件 "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