擅长:python、mysql、java
<p>我没有遵循你的代码,但这里有一个一般的方法来得到你想要的。我使用字符串列表作为输入,而不是列表列表,因为这保证了所有网格单元的长度都是1。你知道吗</p>
<pre><code>def print_grid(grid):
"""Show a list of strings as a grid, with even spacing."""
n_cols = max(map(len, grid))
width = len(str(n_cols-1))
def format_width(value):
fmt = '{{:>{}}}'.format(width)
return fmt.format(value)
header = map(format_width, ('', *range(n_cols)))
print(*header)
for i, s in enumerate(grid):
row = map(format_width, (i, *s))
print(*row)
</code></pre>
<p>试运行:</p>
<pre><code>>>> print_grid(['.' * 5] * 5)
0 1 2 3 4
0 . . . . .
1 . . . . .
2 . . . . .
3 . . . . .
4 . . . . .
>>> print_grid(['.' * 11] * 5)
0 1 2 3 4 5 6 7 8 9 10
0 . . . . . . . . . . .
1 . . . . . . . . . . .
2 . . . . . . . . . . .
3 . . . . . . . . . . .
4 . . . . . . . . . . .
</code></pre>