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

Python2转Python3时矩阵打印格式异常问题求助

Python2代码迁移至Python3后矩阵格式输出异常的修复方案

问题背景

一段Python2编写的代码迁移至Python3运行后,无法输出预期的Markdown矩阵格式,当前输出为混乱的非结构化样式。

原Python2代码

for n in cols:
    print('/t',n),
print
cost = 0

for g in sorted(costs):
    print('\t', g)
    for n in cols:
        y = res[g][n]
        if y != 0:
            print (y),
        cost += y * costs[g][n]
        print ('\t'),
    print
print ("\n\nTotal Cost = ", cost)

预期输出格式

|0 |A |B |C |D |E |
|- |- |- |- |- |- |
|W |  |  |20|  |  |        
|X |  |40|10|  |20|  
|Y |  |20|  |  |30|      
|Z |  |  |  |  |60|  


Total Cost =  1000

修改方案

1. 修复Python3的print语法差异

Python2中print是语句,末尾加逗号会抑制换行;Python3中print是函数,必须用括号调用,抑制换行需要通过end参数实现。同时原代码存在拼写错误:把制表符转义符\t写成了/t,需要修正。

2. 重构输出逻辑,对齐Markdown表格结构

原代码逐元素零散打印的逻辑无法构建|分隔的表格,需要调整为按行拼接完整字符串后一次性输出:

修改后的Python3代码:

# 打印表头行
print('|', end='')
for n in cols:
    print(f' {n} |', end='')
print()

# 打印表格分隔线
print('|', end='')
for _ in cols:
    print(' - |', end='')
print()

cost = 0

# 打印每行数据
for g in sorted(costs):
    print(f'| {g} |', end='')
    for n in cols:
        y = res[g][n]
        # 非0值显示数字,否则显示空格占位
        val = f' {y} ' if y != 0 else '   '
        print(f'{val}|', end='')
        cost += y * costs[g][n]
    print()

# 打印总成本
print(f"\n\nTotal Cost =  {cost}")

3. 关键修改说明

  • 将Python2的print xxx,替换为Python3的print(xxx, end=''),实现同一行内连续输出
  • 修正/t为\t的拼写错误(原代码表头打印的错误转义符会导致格式混乱)
  • 重新设计每行的字符串拼接逻辑,用|分隔每个单元格,严格匹配预期的Markdown表格格式
  • 使用f-string简化字符串拼接(Python3.6及以上支持),若需兼容更早版本,可替换为str.format()写法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:10:24