我正在尝试打印 0 和 1 的列表理解,但它给出了一个错误

I'm trying list comprehensions for printing 0's and 1's but it gives an error

所以基本上我正在尝试打印一个 8x8 网格 有 0 和 1,如下所示:

1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

我需要在嵌套循环中使用它。 我正在使用这段代码,但它不起作用:

def print_board(board):
    board = [1 for i in range(8)] + board[3:]
    board = board[::-1] #reverse
    board = [1 for i in range(8)] + board[3:]
    for i in range(len(board)):
        print(board[i])
        print(" ".join([str(x) for x in board[i]]))
board=[]
for i in range(8):
        board.append([0] * 8)
print_board(board)

错误是:

001 | 1
002 | Traceback (most recent call last):
003 |   File "<string>", line 11, in <module>
004 |   File "<string>", line 7, in print_board
005 | TypeError: 'int' object is not iterable

使用 python

的最新版本 (3.10)

不确定这是否真的是您要找的,但是:

a = []

for i in range(8):
    match i:
        case 3 | 4:
            r = [0] * 8
        case _:
            r = [1] * 8
    a.append(r)

for r in a:
    print(*r)

输出:

1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1