我有这段代码:
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']
要更新我的代码以便管理它的任何想法吗?
谢谢!
答案 0 :(得分:2)
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
答案 1 :(得分:1)
如果board
完全如下,那么您可以将list2
添加到board
,压缩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']
答案 2 :(得分:1)
使用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