在python中,有什么简单的方法可以按浮点数降序排列标准吗?

2024-06-16 10:45:49 发布

您现在位置: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的初学者


Tags: 列表标准fivestatesreadingbasinproperalmost
1条回答
网友
1楼 · 发布于 2024-06-16 10:45:49

用列表排序似乎很自然。您可以按每行(data.split('\n'))末尾的浮点值对行(float(line.split()[-1])排序,并使用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

相关问题 更多 >