-1

如果我在这里有这段代码:

myfile = open("chess.txt", 'r')

line = myfile.readline().rstrip('\n')
while line != '':
    print(line.rstrip('\n'))
    line = myfile.readline().rstrip('\n')

myfile.close()

它打印出这个:

1692 The Rickster
2875 Gary Kasparov
1692 Bobby Fisher
1235 Ben Dover
0785 Chuck Roast
1010 Jim Naysium
0834 Baba Wawa
1616 Bruce Lee
0123 K. T. Frog
2000 Socrates

我需要用什么来按从高到低(数字)的顺序排列它们?

myfile 是放在记事本上的姓名和数字的列表。

4

2 回答 2

2

将您的行读入一个元组列表,并将分数转换为整数以便于数字排序,然后对列表进行排序:

entries = []

with open('chess.txt') as chessfile:
    for line in chessfile:
        score, name = line.strip().split(' ', 1)
        entries.append((int(score), name))

entries.sort(reverse=True)

也就是说,0前面带有 -padded 整数的行也将按字典顺序排序:

with open('chess.txt') as chessfile:
    entries = list(chessfile)

entries.sort(reverse=True)
于 2013-10-29T17:10:09.310 回答
0

即使数字未填充 0,此版本也可以使用。

为避免必须将密钥添加到行中,请使用“密钥”参数sorted

with open('/tmp/chess.txt') as chessfile:
     print ''.join(sorted(chessfile, reverse=True,
                          key=lambda k: int(k.split()[0])))
于 2013-10-29T18:09:49.517 回答