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

如何使用format()将嵌套列表打印为表格并解决list.__format__报错

报错原因与修复方案

错误根因

你遇到的unsupported format string passed to list.__format__报错,是因为str.format()方法不支持直接对列表类型应用宽度格式化规则,需要先将需要打印的列表转换为逗号分隔的字符串后,再传入格式化方法。

修复后可运行代码

data = [[1, [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], 
        [2, [1, 2, -999, 4, 5], [1, 2, 3.0, 4, 5]]]

print("{:<10} {:<20} {:<20}".format('Test Case','Original','Clean-Up'))

for item in data:
    testcase, original, clean = item
    # 先把列表转为逗号分隔的字符串
    original_str = ", ".join(map(str, original))
    clean_str = ", ".join(map(str, clean))
    print("{:<10} {:<20} {:<20}".format(testcase, original_str, clean_str))

输出效果

运行上述代码后输出完全符合预期:

Test Case  Original             Clean-Up            
1          1, 2, 3, 4, 5        1, 2, 3, 4, 5       
2          1, 2, -999, 4, 5     1, 2, 3.0, 4, 5  

内容的提问来源于stack exchange,提问作者Hidden Angle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:51:03