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

Python中如何让输出的帕斯卡三角列表居中显示?

解决帕斯卡三角居中显示问题

我编写了Python代码,可根据指定的三角层数、首行数字数量及具体数字生成帕斯卡三角,但打印各列表时无法实现居中显示,导致输出形态不呈三角状。尝试使用{:^80}格式化方式但未生效,原代码如下:

import math

print("This code is used to calculate pascals triangle starting from any given number and giving a list as long as needed")

layers = int(input("Enter how many layers you want to calculate (Works best if less than 20):"))
num_amount = int(input("Enter how many numbers you want in the first line :"))

pascal_nums = []
for i in range(0, num_amount):
    cur_num = int(input("Enter number here :"))
    pascal_nums.append(cur_num)
pascal_nums.insert(0, 1)
pascal_nums.append(1)
j = 0
while j <= layers:
    print(" ", end="")
    j += 1
print(*pascal_nums)

for i in range(0, layers):
    for i in range(0, len(pascal_nums)-1):
        temp_num = pascal_nums[i] + pascal_nums[i + 1]
        pascal_nums.remove(pascal_nums[i])
        pascal_nums.insert(i, temp_num)
    pascal_nums.insert(0, 1)
    j = i
    while j <= layers:
        print(" ", end="")
        j += 1
    print(*pascal_nums)

问题分析

原代码的核心问题:

  • 直接打印列表元素时未统一数字宽度,数字位数变化(如从个位数变为两位数)会破坏对齐。
  • 前置空格的计算逻辑错误,固定空格数无法适配不同长度的行,且缩进方向与三角形态需求相反。
  • 生成下一行时直接修改原列表,导致索引混乱,同时逻辑冗余。

修复方案

修改思路:

  1. 统一每个数字的显示宽度,确保对齐一致性。
  2. 利用字符串center方法实现自动居中,无需手动计算空格。
  3. 重构行生成逻辑,通过创建新列表避免索引错误。

修改后的代码:

# 可根据需求调整数字显示宽度和整体总宽度
NUM_WIDTH = 4
TOTAL_WIDTH = 80

print("This code is used to calculate pascals triangle starting from any given number and giving a list as long as needed")

layers = int(input("Enter how many layers you want to calculate (Works best if less than 20):"))
num_amount = int(input("Enter how many numbers you want in the first line :"))

# 初始化首行自定义数字
pascal_nums = []
for _ in range(num_amount):
    cur_num = int(input("Enter number here :"))
    pascal_nums.append(cur_num)
# 拼接首尾的1,形成完整首行
current_row = [1] + pascal_nums + [1]

# 格式化并居中打印首行
row_str = "".join(f"{num:{NUM_WIDTH}d}" for num in current_row)
print(row_str.center(TOTAL_WIDTH))

# 生成并打印后续行
for _ in range(layers):
    next_row = [1]
    # 计算下一行的中间数字
    for i in range(len(current_row)-1):
        next_row.append(current_row[i] + current_row[i+1])
    next_row.append(1)
    current_row = next_row
    # 居中打印当前行
    row_str = "".join(f"{num:{NUM_WIDTH}d}" for num in current_row)
    print(row_str.center(TOTAL_WIDTH))

关键说明

  • NUM_WIDTH:控制每个数字占用的字符宽度,确保不同位数的数字对齐整齐。
  • row_str.center(TOTAL_WIDTH):自动计算并添加左右空格,实现行内容的居中显示。
  • 新行生成逻辑:通过创建next_row存储下一行数据,避免直接修改原列表导致的索引混乱,逻辑更清晰可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:53:40