我正在尝试在python 3.5上创建一个看起来像这样的板/网格:
高度/宽度是用户输入。
这就是我目前所拥有的:
board = [['*' for i, row in enumerate(range(2))] for row in enumerate(range(3))]
for i, row in enumerate(board):
actual_board = ' '.join(row)
row_text = '{0} '.format(i)
print (row_text + actual_board)
输出:
0 * *
1 * *
2 * *
答案 0 :(得分:1)
当您创建board
时,您未使用i
或row
- 则无需enumerate()
range()
。只需使用range()
。
board = [['*' for column in range(2)] for row in range(3)]
print(' ' + ''.join(map(str, range(2)))) # print column labels
for row, item in enumerate(board): # for each row
print(str(row) + ''.join(item)) # print the row label and contents
结果:
01
0**
1**
2**
答案 1 :(得分:0)
另一种方法,稍微冗长的代码。
def makeboard(rows, cols):
board = []
for r in range(rows):
brow = []
for c in range(cols):
if r == c == 0:
brow.append(' ')
elif r == 0:
brow.append(str(c-1))
elif c == 0:
brow.append(str(r-1))
else:
brow.append('*')
board.append(brow)
return board
b = makeboard(4,3)
for row in b:
print ' '.join(row)