在 python 中按浮点数降序对标准进行排序的任何简单方法?

any easy way to sort the standard out by the float number in descending order in python?

我的标准输出如下:

seventy-five 0.050
states 0.719
drainage-basin 0.037
scotland 0.037
reading 0.123
thirty-eight 0.000
almost 0.037
rhine 0.000
proper 0.037
contrary 0.087

有什么简单的方法可以根据后面的浮点数按值降序对长标准输出列表进行排序并保持标准输出格式而不是将其转换为列表和排序?抱歉这个愚蠢的问题,因为我是 python 的初学者。

用列表排序似乎很自然。您按每行末尾的浮点值 (float(line.split()[-1]) 对行 (data.split('\n')) 进行排序,并使用 reverse 关键字获得降序。

data = """seventy-five 0.050
states 0.719
drainage-basin 0.037
scotland 0.037
reading 0.123
thirty-eight 0.000
almost 0.037
rhine 0.000
proper 0.037
contrary 0.087"""

result = "\n".join(
    sorted(data.split("\n"), key=lambda s: float(s.split()[-1]), reverse=True)
)

print(result)

# states 0.719
# reading 0.123
# contrary 0.087
# seventy-five 0.050
# drainage-basin 0.037
# scotland 0.037
# almost 0.037
# proper 0.037
# thirty-eight 0.000
# rhine 0.000

如果您厌恶列表,您可以使用命令行工具,例如 sort