[英]I am trying to create a clean 5x5 grid without any brackets, quotes, or commas
The following is my code:以下是我的代码:
...
self.__treasure_map = size
self.__chest_positions = chests
self.__tree_positions = trees
self.__num_chests_found = 0
self.grid=[]
for i in range(self.__treasure_map):
self.grid.append([])
for j in range(self.__treasure_map):
self.grid[i].append(TreasureMap.UNSEARCHED_CHAR)
def display_map(self):
print(' ', end="")
for i in range(self.__treasure_map):
count = 0
print(' ',count+i,end='')
print('\n',end ='')
for i in self.grid:
self.grid[count][0] = count
count+=1
print(i)
This is my grid after printing out:这是我打印出来后的网格:
However, this is the outcome I want然而,这就是我想要的结果
I think this may at least be close to what you want:我认为这可能至少接近你想要的:
class TreasureMap:
UNSEARCHED_CHAR = '.'
class MyClass:
def __init__(self, size, chests, trees):
self.__treasure_map = size
self.__chest_positions = chests
self.__tree_positions = trees
self.__num_chests_found = 0
self.grid=[]
for i in range(self.__treasure_map):
self.grid.append([])
for j in range(self.__treasure_map):
self.grid[i].append(TreasureMap.UNSEARCHED_CHAR)
def display_map(self):
print(' ', ' '.join(str(i) for i in range(self.__treasure_map)))
for i in range(self.__treasure_map):
print('{:>2}'.format(i), ' '.join(elem for elem in self.grid[i]))
if __name__ == '__main__':
obj = MyClass(5, 1, 2)
obj.display_map()
Output: Output:
0 1 2 3 4
0 . . . . .
1 . . . . .
2 . . . . .
3 . . . . .
4 . . . . .
I'm not following your code, but here's a general way to get what you want.我没有遵循您的代码,但这是获得您想要的东西的一般方法。 I'm using a list of strings as input instead of a list of lists because that guarantees all the grid cells will be exactly 1-long.
我使用字符串列表而不是列表列表作为输入,因为这样可以保证所有网格单元的长度都为 1。
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)
Test run:测试运行:
>>> 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 . . . . . . . . . . .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.