You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将列表输出为带表头的表格并按百分比降序排序

问题解决

排序不生效原因

sorted() 是Python内置函数,不会修改传入的原始列表,只会返回一个排序完成的新列表。你之前的代码没有将sorted()的返回结果赋值给变量,所以原数据没有变化,看起来就像排序没有生效。

完整实现代码

# 原始输出数据
rank_values_perc = [(22, 8, 40.0), (23, 1, 5.0), (24, 1, 5.0), ('Friday', 2, 10.0), ('Monday', 4, 20.0), ('Thursday', 2, 10.0), ('Tuesday', 1, 5.0), ('Wednesday', 1, 5.0)]

# 正确排序写法:接收sorted返回的排序后新列表
sorted_data = sorted(rank_values_perc, key=lambda x: x[2], reverse=True)

# 输出Markdown格式表格
print("| Value | Count | Percentage |")
print("| --- | --- | --- |")
for value, count, perc in sorted_data:
    print(f"| {value} | {count} | {perc} |")

最终输出效果

运行上述代码后得到的按百分比降序排列的表格如下:

ValueCountPercentage
22840.0
Monday420.0
Friday210.0
Thursday210.0
2315.0
2415.0
Tuesday15.0
Wednesday15.0

如果需要在控制台打印对齐的纯文本表格,可以使用以下代码:

# 控制台对齐表格输出
header = f"{'Value':<10} {'Count':<6} {'Percentage':<10}"
print(header)
print("-" * len(header))
for value, count, perc in sorted_data:
    print(f"{str(value):<10} {count:<6} {perc:<10}")

内容的提问来源于stack exchange,提问作者Matt Lightbourn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:54:03