如何创建2d网格?

时间:2014-07-29 22:20:09

标签: python list python-3.x

所以当我尝试制作2D网格时出现此错误。我知道它看起来我的列表中没有5行。那是错误。这是我试过的:

board = ["O", "O", "O", "O", "O"]

    def create_board(width, height, empty='O'):
        for x in range(5):
            board.append(board)
            return board
        return            

a = create_board(5, 5)
print(a)  # show "empty" board that was created

2 个答案:

答案 0 :(得分:1)

a_2d_list = [
             [r,o,w,1],
             [r,o,w,2],
             ...]

是你的意思吗?

board = [["O", "O", "O", "O", "O"] for _ in range(0, 5)]
print "\n".join(map(" ".join,board))

答案 1 :(得分:0)

你的意思是这样的吗?

def create_board(width, height, empty='O'):
    return [[empty for _ in range(width)] for _ in range(height)]

board = create_board(3, 4)
print(board)  # show "empty" board that was created

board[1][1] = 'X'
print(board)  # show board after modification

输出:

[['O', 'O', 'O'], ['O', 'O', 'O'], ['O', 'O', 'O'], ['O', 'O', 'O']]
[['O', 'O', 'O'], ['O', 'X', 'O'], ['O', 'O', 'O'], ['O', 'O', 'O']]