简体   繁体   English

在 python 中以一行打印形状

[英]printing shapes in one line in python

I am trying to print 2 circles pattern in one row and two in the next row like this我正在尝试在一行中打印 2 个圆形图案,在下一行中打印两个,如下所示

在此处输入图像描述

Here is my Code:这是我的代码:

cell = {}
row = 5
col = 5

for i in range(0,row):
    for j in range(0,col):
        if((j == 0 or j == col-1) and (i!=0 and i!=row-1)) :
            cell[(i,j)] = '*'
                   #end='' so that print statement should not change the line.
        elif( ((i==0 or i==row-1) and (j>0 and j<col-1))):
            cell[(i,j)] = '*'
        else:
            cell[(i,j)] = " "
        print(cell[(i, j)], end=" ")
    print(end='\n')

And with this code I'm getting the output as follows:使用此代码,我得到 output 如下:

在此处输入图像描述

what should I change in this code to make it correct?我应该在此代码中进行哪些更改以使其正确?

You essentially need a template for top/bottom of a circle and the middle part of a circle.您基本上需要一个圆的顶部/底部和圆的中间部分的模板。

Then you need to print enough of them per line:然后你需要每行打印足够的它们:

nums = 7   # only squares supported
amount = 3 # shapes per line & shape rows in total
spacer = 2 # space horizontally, vertically it is 1 line

# prepare shapes
top_botton = f" {'*'*(nums-2)} "
middle = f"*{' '*(nums-2)}*"
space_h = " " * spacer

for row in range(amount * nums):
    # detect which row we are in
    mod_row = row % nums     

    # bottom or top of row
    if mod_row in (0, nums-1):
        print(*([top_botton]*amount), sep=space_h )
        if mod_row == nums-1:
            print()

    # middle of row
    else:
        print(*([middle]*amount), sep=space_h)            

Output: Output:

# nums = 5, count = 2
 ***    *** 
*   *  *   *
*   *  *   *
*   *  *   *
 ***    ***

 ***    ***
*   *  *   *
*   *  *   *
*   *  *   *
 ***    ***

# nums = 7, count = 3
 *****    *****    ***** 
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
 *****    *****    *****

 *****    *****    *****
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
 *****    *****    *****

 *****    *****    *****
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
*     *  *     *  *     *
 *****    *****    *****

The distance between the circles is handled by the sep=... of the print statement.圆圈之间的距离由 print 语句的sep=...处理。 It prints the decomposed list of (amount) shapes.它打印(数量)形状的分解列表。

You could as well handle a "single char" printer like you did for your single cirle, but all those loops in loops and values modular checking are getting confusing fast.您也可以像处理单个圆圈一样处理“单个字符”打印机,但是循环和值模块化检查中的所有这些循环都很快变得令人困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM