如何正确显示 python 中的图板?

How to show a board in python correctly?

我想展示一个类似于数独游戏的棋盘: 结果有一些我不想要的括号 我不想要最后一行

board = [
[
 [
  [None, None, None], [None, None, None], [None, None, None],
 ],
 [
  [None, None, None], [None, None, None], [None, None, None],
 ],
 [
  [None, None, None], [None, None, None], [None, None, None],
 ]
],
[
 [
  [None, None, None], [None, None, None], [None, None, None],
 ],
 [
  [None, None, None], [None, None, None], [None, None, None],
 ],
 [
  [None, None, None], [None, None, None], [None, None, None],
 ]
],
[
 [
  [None, None, None], [None, None, None], [None, None, None],
 ],
 [
  [None, None, None], [None, None, None], [None, None, None],
 ],
 [
  [None, None, None], [None, None, None], [None, None, None],
 ]
],

]

for sq in board:
   for row in sq:
       print('|', end='')
       for cell in row:
           print(cell, end='|')
       print()
   print('+', '------------------+'*3, sep='')

如果有人帮助我,我会很高兴

这是因为变量 cell 是一个列表,这就是列表的打印方式。要修复它,您必须遍历 cell

您可以使用列表解包操作符*。进行以下更改

for cell in row:
    # print(cell, end='|')
    print(*cell, end='|')

此外,元素之间的默认分隔符是 " "
如果您想将其更改为其他内容,请在 print() 语句

中使用 sep 关键字

你有括号的原因是因为你正在打印列表。

将列表的所有值解包或打印为单个值的一种方法是使用 for 循环:

>>> items = ["apple", "ball", "car"]
>>> for item in items:
>>>    # Printing the values on the same line
>>>    print(item, end="")
>>> apple ball car 

您可以做的另一件事是使用 Python 中的一项很酷的功能,将列表解压在一行中,我们使用星号 (*) 来执行此操作:

>>> items = ["apple", "ball", "car"]
>>> print(*items)
>>> apple ball car

这是完整的代码,包括对没有最后一行的修复:

# There are 3 squares and we dont want the line after the 3rd block.
# So we are using 'count' in order to keep track in which square
# we are in.
count = 1
for sq in board:
   for row in sq:
       print('|', end='')
       for cell in row:
           # By using a * we can unpack the list without having
           # to use a for loop
           print(*cell, end='|')
       print()
   # If we are in the 3rd square dont include a line
   if count != 3: 
    print('+', '--------------+'*3, sep='')
   
   count+=1

您可以将其打印为 numpy 数组:

import numpy

print(numpy.array(board))

输出:

[[[[None None None]
   [None None None]
   [None None None]]

  [[None None None]
   [None None None]
   [None None None]]

  [[None None None]
   [None None None]
   [None None None]]]


 [[[None None None]
   [None None None]
   [None None None]]

  [[None None None]
   [None None None]
   [None None None]]

  [[None None None]
   [None None None]
   [None None None]]]


 [[[None None None]
   [None None None]
   [None None None]]

  [[None None None]
   [None None None]
   [None None None]]

  [[None None None]
   [None None None]
   [None None None]]]]