打印列表格式列表

时间:2014-01-29 08:17:53

标签: list python-3.x format

python编程相当新。我试图从给定的列表列表中创建一个模式。这是我的代码:

NONE = ''

Column = 7
Rows = 6

def new_game_board() -> [[str]]:

   board = []

   for col in range(BOARD_COLUMNS):
      board.append([])
      for row in range(BOARD_ROWS):
         board[-1].append(NONE)
return board


gb = new_game_board()

for item in gb:
   print(item)

董事会看起来像这样:

['', '', '', '', '', '']
['', '', '', '', '', '']
['', '', '', '', '', '']
['', '', '', '', '', '']
['', '', '', '', '', '']
['', '', '', '', '', '']
['', '', '', '', '', '']

然而,它应该是:

1  2  3  4  5  6  7
*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *

如何将列表格式化为上面的模式。

2 个答案:

答案 0 :(得分:1)

Columns = 7
Rows = 6

def new_game_board() -> [[str]]:
   board = [ ''.join('%3i' % i for i in range(1, 1 + Columns))  ]
   board += Rows*[ Columns*'  *' ]
   return board

gb = new_game_board()

for item in gb:
   print(item)

这会产生输出:

  1  2  3  4  5  6  7
  *  *  *  *  *  *  *
  *  *  *  *  *  *  *
  *  *  *  *  *  *  *
  *  *  *  *  *  *  *
  *  *  *  *  *  *  *
  *  *  *  *  *  *  *

ALTERNATIVELY:假设我们保留现有的new_game_board函数(拼写错误已修复)并添加打印功能:

NONE = ''

Columns = 7
Rows = 6

def new_game_board() -> [[str]]:
   board = []
   for row in range(Rows):
       board.append([])
       for col in range(Columns):
           board[-1].append(NONE)
   return board

def print_board(board):
   print(''.join('%3i' % i for i in range(1, 1 + len(board[0]))))
   for item in board:
       print(''.join('%3s' % (v if v else '*') for v in item))

gb = new_game_board()
print_board(gb)

这产生与上面相同的输出。

答案 1 :(得分:1)

如果您将您的电路板作为课程,您可以定义__str__方法为您执行此操作:

class Board(object):

    def __init__(self, r, c, val="*"):
        self.r = r
        self.c = c
        self.tiles = [[j+1 for j in range(c)]]
        self.tiles += [[val for j in range(c)] for i in range(r)] 

    def __str__(self):
        return "\n".join(" ".join(str(c) for c in self.tiles[r])
                         for r in range(len(self.tiles)))

现在print(Board(6, 7))给出:

1 2 3 4 5 6 7
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *

此方法允许您在幕后制作列表列表,但以用户友好的方式显示,还允许您定义常见的棋盘游戏操作(例如“将片段从(r1,c1)移动到(r2) ,c2)“)作为实例方法。