我有这个代码:
def __repr__(self):
"""
:return: Return a string representation of the board.
"""
list1=['0','1','2','3','4','5','-']
list2=['0','1','2','E','4','5']
output=''
for row in self.board:
output=output+str(row)+'\n'
return output
self.board
是下面的输出列表,
这个矩阵的输出为字符串:
['_', '_', '_', 'R', '_', '_']
['_', '_', '_', 'R', '_', '_']
['_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_']
['p', 'p', '_', '_', '_', '_']
现在,正如我在代码中看到的那样,我已经定义了两个列表,我想将list1
添加为此字符串中的第一列,并将list2
添加为最后一行,我仍然无法弄清楚我怎么能这样做呢..
这是我想要做的输出:
['0', '_', '_', '_', 'R', '_', '_']
['1', '_', '_', '_', 'R', '_', '_']
['2', '_', '_', '_', '_', '_', '_']
['3', '_', '_', '_', '_', '_', '_']
['4', '_', '_', '_', '_', '_', '_']
['5', 'p', 'p', '_', '_', '_', '_']
['-', '0', '1', '2', 'E', '4', '5']
有什么想更新我的代码以便管理它?
谢谢!
def __repr__(self):
"""
:return: Return a string representation of the board.
"""
list1=['0','1','2','3','4','5','-']
list2=['0','1','2','E','4','5']
output=''
for x in xrange(len(self.board)):
output = output + str([list1[x]] + self.board[x])+'\n'
output = output + str([list1[-1] + list2) + '\n'
return output
如果board
完全如下,那么你可以将list2
添加到board
,zip board
,然后用board
中的值将每行list1
压缩:
board = [['_', '_', '_', 'R', '_', '_'],
['_', '_', '_', 'R', '_', '_'],
['_', '_', '_', '_', '_', '_'],
['_', '_', '_', '_', '_', '_'],
['_', '_', '_', '_', '_', '_'],
['p', 'p', '_', '_', '_', '_']]
list1=['0','1','2','3','4','5','-']
list2=['0','1','2','E','4','5']
final_board = [[a]+list(c) for a, c in zip(list1, list(zip(board+[list2])))]
new_final_board = [[a, *b] for a, b in final_board]
输出:
['0', '_', '_', '_', 'R', '_', '_']
['1', '_', '_', '_', 'R', '_', '_']
['2', '_', '_', '_', '_', '_', '_']
['3', '_', '_', '_', '_', '_', '_']
['4', '_', '_', '_', '_', '_', '_']
['5', 'p', 'p', '_', '_', '_', '_']
['-', '0', '1', '2', 'E', '4', '5']
使用enumerate
操作,您可以获取索引和数组中的对象。
这样,您可以在打印线之前打印正确的字符,然后打印最后一行。
def __repr__(self):
"""
:return: Return a string representation of the board.
"""
list1 = ['0','1','2','3','4','5']
list2 = ['-','0','1','2','E','4','5']
output = ''
for rowNumber, row in enumerate(self.board):
output = list1[rowNumber] + output + str(row)+'\n'
output = output + str(list2)
return output