我试图创建一个干净的5x5网格没有任何括号,引号或逗号

2024-03-28 15:41:49 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的代码:

...
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)

这是我打印出来的网格:

enter image description here

然而,这是我想要的结果

enter image description here


Tags: 代码inselfmapforsizecountrange
2条回答

我认为这可能至少接近你想要的:

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()

输出:

   0 1 2 3 4
 0 . . . . .
 1 . . . . .
 2 . . . . .
 3 . . . . .
 4 . . . . .

我没有遵循你的代码,但这里有一个一般的方法来得到你想要的。我使用字符串列表作为输入,而不是列表列表,因为这保证了所有网格单元的长度都是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)

试运行:

>>> 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  .  .  .  .  .  .  .  .  .  .  .

相关问题 更多 >