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

时间:2013-05-02 20:59:45

标签: 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

输出:

['B', 'W', 'B']
['W', 'B', 'W']
['B', 'W', 'B']

7 个答案:

答案 0 :(得分: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']]

答案 1 :(得分:2)

有点黑客但是

print [["B" if abs(n - row) % 2 == 0 else "W" for n in xrange(3)] for row in xrange(3)][::-1]

这似乎是需求蔓延或某事=)

def make_board(n):
    ''' returns an empty list for n <= 0 '''
    return [["B" if abs(c - r) % 2 == 0 else "W" for c in xrange(n)] for r in xrange(n)][::-1]

答案 2 :(得分:2)

以下是itertools解决方案:

from itertools import cycle
N = 4

colors = cycle(["W","B"])
row_A  = [colors.next() for _ in xrange(N)]
if not N%2: colors.next()
row_B  = [colors.next() for _ in xrange(N)]

rows = cycle([row_A, row_B])
board = [rows.next() for _ in xrange(N)]

对于N=4,这给出了

['W', 'B', 'W', 'B']
['B', 'W', 'B', 'W']
['W', 'B', 'W', 'B']
['B', 'W', 'B', 'W']

如果你确保将每个新行和周期添加到行列表中,这应该可以扩展为多种颜色(例如一个“B”,“W”,“G”的板)。

答案 3 :(得分:0)

for i in range(len(board)):
    for j in range(len(board)):
        if isEven(i + j + len(board)):
            board[i][j] = "W"

答案 4 :(得分:0)

这个正确地将左下角设置为'B',始终:

def board(n):
    def line(n, offset):
        return [(i+offset) % 2 and 'W' or 'B' for i in range(n)]
    return [line(n,i) for i in range(n+1,1,-1)]

答案 5 :(得分:0)

粗暴易懂。另外,可以生成矩形板:

def gen_board(width, height):
    bw = ['B', 'W']
    l = [[bw[(j + i) % 2] for j in range(width)] for i in range(height)]
    # this is done to make sure B is always bottom left
    # alternatively, you could do the printing in reverse order
    l.reverse()

    ## or, we could ensure B is always bottom left by adjusting the index
    #offset = height%2 + 1
    #l = [[bw[(j + i + offset) % 2] for j in range(width)] for i in range(height)]
    return l

def print_board(b):
    for row in b:
        print row

试驾:

>>> print_board(gen_board(4, 3))
['B', 'W', 'B', 'W']
['W', 'B', 'W', 'B']
['B', 'W', 'B', 'W']

答案 6 :(得分:0)

使用单行numpy代码,不带for循环:

import numpy as np

chessbool = (np.arange(3)[:, None] + np.arange(3)) % 2 == 0

,输出为:

array([[ True, False,  True],
       [False,  True, False],
       [ True, False,  True]]

使用WB填充数组:

chessboard = np.where(chessbool,'B','W')

,输出为:

array([['B', 'W', 'B'],
       ['W', 'B', 'W'],
       ['B', 'W', 'B']])