简体   繁体   English

如何优化模式并删除输出中的括号?

[英]How to refine the pattern and remove the brackets in output?

I am trying to write a function that prints a diagonal pattern.我正在尝试编写一个打印对角线图案的函数。 The arguments to this are:对此的论据是:

  1. The number of columns (stars) in each line每行的列数(星号)
  2. The number of lines行数
  3. The length of the gap between two consecutive stars on each line.每条线上两个连续星之间的间隙长度。

This is what I have tried:这是我尝试过的:

def pattern(s, r, g):
    for i in range(r):
        print(" " * g, ("*", " " * g) * s, end="\n")

But the output looks like this: for pattern(2,3,4) where 2 is the number of stars in each row, 3 is the number of rows and 4 is the number of gaps between the stars但是输出看起来像这样:对于 pattern(2,3,4),其中 2 是每行中的星星数,3 是行数,4 是星星之间的间隙数

('*', '    ', '*', '    ')
('*', '    ', '*', '    ')
('*', '    ', '*', '    ')

How can I execute this without the brackets?如何在没有括号的情况下执行此操作?

You are printing out tuples.您正在打印元组。 You need to unpack tuple using * operator:您需要使用*运算符解包元组:

def pattern(s, r, g):
    for i in range (r):
        print(' ' * g, *('*', ' ' * g) * s, end='\n')

pattern(2, 3, 4)

Output :输出

     *      *
     *      *                                                    
     *      *                                            

You can add one more loop您可以再添加一个循环

    for i in range (r):
        for j in range(s):
            print('*', ' '*g, end='')
        print('\n')

pattern(3,5,8)

Output :输出 :

*         *         *         

*         *         *         

*         *         *         

*         *         *         

*         *         *

Alternatively to printing out tuples / expanding the tuples, you could simply print a string built by concatenating the different string parts using + , eg或者打印出元组/扩展元组,您可以简单地打印通过使用+连接不同字符串部分构建的字符串,例如

def pattern(s, r, g):
    for i in range(r):
        print(" " * g + ("*" + " " * g) * s, end="\n")


pattern(2, 3, 4)

Output:输出:

     *      *
     *      *                                                    
     *      * 

Note that end="\\n" is superfluous here, and there seems to be no diagonal pattern.注意这里end="\\n"是多余的,而且似乎没有对角线模式。

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

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