如何组合4个三角形的循环来制作"钻石"?

2 python while-loop python-2.7

我想制作这个"钻石":

********************
*********  *********
********    ********
*******      *******
******        ******
*****          *****
****            ****
***              ***
**                **
*                  *
*                  *
**                **
***              ***
****            ****
*****          *****
******        ******
*******      *******
********    ********
*********  *********
********************
Run Code Online (Sandbox Code Playgroud)

我可以制作使用while循环制作钻石的4个三角形:

x = 10
while 0 < x < 11:
    print '%10s' % ('*' * x),
    x = x - 1
    print

x = 0
while x < 11:
    print '%10s' % ('*' * x),
    x = x + 1
    print

x = 10
while 0 < x < 11:
    print '%0s' % ('*' * x),
    x = x - 1
    print

x = 0
while x < 11:
    print '%0s' % ('*' * x),
    x = x + 1
    print
Run Code Online (Sandbox Code Playgroud)

我可以将这4个循环组合在一起制作钻石吗?或者我必须以不同的方式做到这一点?

ssh*_*124 6

我建议你使用字符串格式化(你可以试验参数):

a = range(0,20,2)+range(20,-1, -2)

for i in a:
    print '{:*^30}'.format(' '*i)

[OUTPUT]
******************************
**************  **************
*************    *************
************      ************
***********        ***********
**********          **********
*********            *********
********              ********
*******                *******
******                  ******
*****                    *****
******                  ******
*******                *******
********              ********
*********            *********
**********          **********
***********        ***********
************      ************
*************    *************
**************  **************
******************************
Run Code Online (Sandbox Code Playgroud)

上面的代码是什么,它首先创建一个列表a,其中包含每行的空格数.然后字符串格式化为长度列表中的每个元素打印一行30(其中30个部分{:*^30}居中^并在两侧填充*.希望有帮助.

或者只是为了好玩:单行:

for i in range(1,20,2)+range(19,-1, -2):print '{:*^30}'.format(' '*i)