Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何按降序排列列表元素?_Python_Sorting_File Io_Python 3.x - Fatal编程技术网

Python:如何按降序排列列表元素?

Python:如何按降序排列列表元素?,python,sorting,file-io,python-3.x,Python,Sorting,File Io,Python 3.x,如果我这里有这个代码: 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 Fishe

如果我这里有这个代码:

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是放在记事本上的名称和数字列表。

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

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填充整数的行也将按字典顺序排序:

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

entries.sort(reverse=True)

即使数字不是0填充的,这个版本也可以工作

为避免将键添加到行中,请使用键参数来排序:


嗨,欢迎来到stack overflow。你试过什么?什么不起作用?你看过python列表文档了吗?@UpAndAdam:这不是字母排序;这是一个相反的数字排序。@MartijnPieters Thank没有注意到这一部分,删除了重复项,并更新了我的答案,并提供了排序文档的链接,以解释所有可用的选项。博比·费舍尔(Bobby Fisher),业余垂钓者,1692级patzer,不能与2785级大师、前世界冠军博比·费舍尔(Bobby Fischer)混淆。
with open('/tmp/chess.txt') as chessfile:
     print ''.join(sorted(chessfile, reverse=True,
                          key=lambda k: int(k.split()[0])))