我将如何打印正方形的两条对角线?

How would I print two diagonals of a square?

例如,如果用户输入 2,输出将是 xo ox,如果用户输入 3,它将输出 xox oxo xox 等等。我目前的代码只输出正方形的对角线在相反的方向。

size = int(input("Size of the square: "))

for i in range(size):
    line = ""

    for j in range(size):
        if i+j == size-1:
            line += "x"
        else:
            line += "o"

    print(line)

在这个例子中,当你输入 3 时,你会得到一个输出:

oox
oxo
xoo
size = int(input("Size of the square: "))

for i in range(size):
    line = ""

    for j in range(size):
        if i == j:               # main diagonal
            line += "x"
        elif i + j == size - 1:  # secondary diagonal
            line += "x"
        else:
            line += "o"

    print(line)

您可以使用 numpy fill_diagonal 以获得更有效的方法

size = 3
a = np.chararray((size, size))
a[:] = 'o'
np.fill_diagonal(a, 'x')
np.fill_diagonal(np.fliplr(a), 'x')

输出

a = chararray([[b'x', b'o', b'x'],
               [b'o', b'x', b'o'],
               [b'x', b'o', b'x']], dtype='|S1')

如果你爱上发电机

square = "\n".join(["".join(["x" if i == j or i == size - j - 1 else "o" for j in range(size)]) for i in range(size)])

您可以使用一个循环解决它,如下所示:

size = 3
result = []
for x in range(size)[::-1]:
    line = list("o" * size)
    line[x] = "x"
    result.append("".join(line))
print(*result)