在二维数组中创建黑白棋盘

4d4*_*d4c 5 python

是否有更好(和更短)的方式来创建像数组一样的棋盘.董事会的要求是:

  • 板可以是不同的大小(在我的例子中它是3x3)
  • 板的左下方应始终为黑色
  • 黑色方块呈现"B",白色方块呈现"W"

我有的代码:

def isEven(number):
    return number % 2 == 0

board = [["B" for x in range(3)] for x in range(3)]
if isEven(len(board)):
    for rowIndex, row in enumerate(board):
        if isEven(rowIndex + 1):
            for squareIndex, square in enumerate(row):
                if isEven(squareIndex + 1):
                    board[rowIndex][squareIndex] = "W"
        else:
            for squareIndex, square in enumerate(row):
                if not isEven(squareIndex + 1):
                    board[rowIndex][squareIndex] = "W"
else:
    for rowIndex, row in enumerate(board):
        if not isEven(rowIndex + 1):
            for squareIndex, square in enumerate(row):
                if isEven(squareIndex + 1):
                    board[rowIndex][squareIndex] = "W"
        else:
            for squareIndex, square in enumerate(row):
                if not isEven(squareIndex + 1):
                    board[rowIndex][squareIndex] = "W"

for row in board:
    print row
Run Code Online (Sandbox Code Playgroud)

输出:

['B', 'W', 'B']
['W', 'B', 'W']
['B', 'W', 'B']
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 10

怎么样:

>>> n = 3
>>> board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)]
>>> print board
[['B', 'W', 'B'], ['W', 'B', 'W'], ['B', 'W', 'B']]
>>> n = 4
>>> board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)]
>>> print board
[['W', 'B', 'W', 'B'], ['B', 'W', 'B', 'W'], ['W', 'B', 'W', 'B'], ['B', 'W', 'B', 'W']]
Run Code Online (Sandbox Code Playgroud)