【问题标题】:Python: How do I arrange a list elements in descending order? [closed]Python:如何按降序排列列表元素? [关闭]
【发布时间】:2013-10-29 17:06:25
【问题描述】:

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

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

【问题讨论】:

  • 您好,欢迎来到堆栈溢出。你试过什么?什么没有奏效?你看过python列表文档吗?
  • @UpAndAdam:这不是字母排序;这是反向数字排序..
  • @MartijnPieters 感谢没有注意到那部分,删除了重复并更新了我的答案,其中包含指向排序文档的链接以解释所有可用选项。
  • 鲍比·费舍尔是一名业余垂钓者和 1692 级的捕猎者,不要与前世界冠军、2785 级的大师级博比·费舍尔相混淆。

标签: python sorting file-io python-3.x


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

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

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

    with open('/tmp/chess.txt') as chessfile:
         print ''.join(sorted(chessfile, reverse=True,
                              key=lambda k: int(k.split()[0])))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2014-07-06
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多