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

2024-04-18 03:48:26 发布

您现在位置: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']

Tags: inboardnumberforifnotelse方块
3条回答

这里有一个^{}解决方案:

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”)。

怎么样:

>>> 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']]

有点怪,但是

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]

相关问题 更多 >