How to split rows while printing a pattern in Python
输入:4, 4预期输出:
1 2 3 4 | **** *..* *..* **** |
我的输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | * * * * * . . * * . . * * * * * |
我的代码:
1 2 3 4 5 6 | for i in range(1, 5): for j in range(1, 5): if i == 1 or i == 4 or j == 1 or j == 4: print("*") else: print(".") |
首先,你可以尝试这样做:
1 2 3 4 5 6 7 | for i in range(1, 5): for j in range(1, 5): if i == 1 or i == 4 or j == 1 or j == 4: print"*", else: print".", print '' |
","停止打印命令打印
更新:然后,当然,在完成的行之后添加换行符。
这是使用reduce的一行:
1 2 3 | import sys reduce(lambda x,z:reduce(lambda x,y : sys.stdout.write("*") if y == 1 or y == 4 or z==1 or z==4 else sys.stdout.write("."),range(1,5),None)or sys.stdout.write(" "),range(1,5),None) |
O/P:
1 2 3 4 | **** *..* *..* **** |
否则请尝试使用循环:
1 2 3 4 5 6 7 8 | for i in range(1, 5): for j in range(1,5): if i==1 or j==1 or i==4 or j==4: sys.stdout.write("*") else: sys.stdout.write(".") sys.stdout.write(" ") |
相同O/P
您可以将输出存储在变量中,并且只能在外部循环中打印:
1 2 3 4 5 6 7 8 | for i in range(1, 5): line ="" for j in range(1, 5): if i == 1 or i == 4 or j == 1 or j == 4: line = line +"*" else: line = line +"." print line |
输出为:
1 2 3 4 | **** *..* *..* **** |