You need to enable JavaScript to run this app. Python如何将垂直打印的多道算术题转为横向并排展示?
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将垂直打印的多道算术题转为横向并排展示?

这个需求完全可以实现。核心调整思路是:原来的逻辑是逐道题打印完整的4行内容,自然会纵向排列;改成按行类型批量打印即可——先拼接所有题的第一行(第一操作数行)统一打印,再拼接所有题的第二行(运算符+第二操作数行)打印,以此类推即可实现横向并排效果。

修改后的代码如下:

import operator 

a = ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]


def arithmetic(l, show_answer=None):
    ops = {
        '+': operator.add,
        '-': operator.sub
    }

    def get_max_len(a, b):
        return len(a) if len(a) > len(b) else len(b)
    
    # 初始化四个列表,分别存储所有题对应的4行内容
    line1 = []
    line2 = []
    line3 = []
    line4 = []

    for i in l:
        argfinder = i.find(" ")
        a1 = i[0:argfinder]
        a2 = i[argfinder+3:]
        op = i[argfinder+1]
        out = str(ops.get(op)(int(a1), int(a2)))
        max_num_len = get_max_len(a1, a2)
        dash = "-" * (max_num_len + 2)
        spaceout = " " * abs(len(dash) - len(out))

        if len(a1) <= len(a2):    
            spacea1 = " " * (abs(len(a1)-len(a2)) + 2)
            # 不直接打印,追加到对应行列表
            line1.append(spacea1 + a1)
            line2.append(f"{op} {a2}")
            line3.append(dash)
            line4.append(spaceout + out)
        else:
            spacea1 = " " * (abs(len(dash) - max_num_len))
            spacea2 = " " * abs(len(a1)-len(a2))
            line1.append(spacea1 + a1)
            line2.append(f"{op} {spacea2 + a2}")
            line3.append(dash)
            line4.append(spaceout + out)
    
    # 所有题处理完后,按行拼接打印,题与题之间加4个空格分隔
    gap = "    "
    if show_answer:
        print(gap.join(line1))
        print(gap.join(line2))
        print(gap.join(line3))
        print(gap.join(line4))


arithmetic(a, True)

运行后输出效果和你期望的完全一致:

32      3801      45      123
+ 698    -    2    + 43    +  49
-----    ------    ----    -----
  730      3799      88      172

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 19:36:03