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

Python打印图形问题:如何输出每行两个圆形的多行排列图案

修改方案

你当前的代码仅实现了单个5x5的空心矩形输出,要实现2行2列共4个空心图形的排列效果,需要调整坐标判断逻辑,加入多图形的位置映射,具体修改如下:

  • 新增单图形尺寸、排列数量、图形间距的参数定义,方便调整效果
  • 将全局行列坐标转换为单个图形内的局部坐标,复用原有空心图形判断逻辑
  • 调整打印规则,对图形间隔区域统一输出空格

可直接运行的修改后代码:

# 单个空心图形的参数
single_row = 5
single_col = 5
# 排列参数:2行2列,对应每行2个、共2行的需求
total_shape_rows = 2
total_shape_cols = 2
# 图形之间的横向、纵向间隔,可自行调整大小
gap_col = 2
gap_row = 1

# 计算全局总行列数
total_row = total_shape_rows * single_row + (total_shape_rows - 1) * gap_row
total_col = total_shape_cols * single_col + (total_shape_cols - 1) * gap_col

for global_i in range(total_row):
    # 计算当前行归属的图形序号、图形内的局部行号
    shape_row_idx = global_i // (single_row + gap_row)
    local_i = global_i % (single_row + gap_row)
    # 间隔行直接输出整行空格
    if local_i >= single_row:
        print(' ' * total_col)
        continue
    for global_j in range(total_col):
        # 计算当前列归属的图形序号、图形内的局部列号
        shape_col_idx = global_j // (single_col + gap_col)
        local_j = global_j % (single_col + gap_col)
        # 间隔列直接输出空格
        if local_j >= single_col:
            print(' ', end='')
            continue
        # 复用原有空心图形判断逻辑
        if (local_j == 0 or local_j == single_col - 1) and (local_i != 0 and local_i != single_row - 1):
            print('*', end='')
        elif (local_i == 0 or local_i == single_row - 1) and (local_j > 0 and local_j < single_col - 1):
            print('*', end='')
        else:
            print(' ', end='')
    print()

圆形效果优化:

如果要让输出更接近圆形而非矩形,可将单个图形尺寸调大(比如single_row=7、single_col=9),并去掉四个角的*,将判断逻辑修改为:

if (local_j == 0 or local_j == single_col - 1) and (local_i != 0 and local_i != single_row - 1):
    print('*', end='')
# 新增四个角点位的排除逻辑
elif (local_i == 0 or local_i == single_row - 1) and (1 < local_j < single_col - 2):
    print('*', end='')
else:
    print(' ', end='')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:24:06