-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先頭に -paded 整数を含む行は、辞書順でもソートされます。

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 に答える