如何以数独格式输出

时间:2012-09-28 13:24:24

标签: python python-3.x

如何使用类似于sudoku的行输出以下数据

p = [
    [-8, 0,  0,  0,  0,  0,   0,  0, 0],
    [0,  0, -3, -6,  0,  0,   0,  0, 0],
    [0, -7,  0,  0, -9,  0,  -2,  0, 0],
    [0, -5,  0,  0,  0, -7,   0,  0, 0],
    [0,  0,  0,  0, -4, -5,  -7,  0, 0],
    [0,  0,  0, -1,  0,  0,   0, -3, 0],
    [0,  0, -1,  0,  0,  0,   0, -6, -8],
    [0,  0, -8, -5,  0,  0,   0,  -1, 0],
    [0, -9,  0,  0,  0,  0,  -4,   0, 0]]
print ("Unsolved:")

w="\n".join(re.findall("(?p).{,9}", p))[:-1]
print (w)

以下列方式获取输出

0 | 0 | 3 | 0 | 2 | 0 | 6 | 0 | 0
9 | 0 | 0 | 3 | 0 | 5 | 0 | 0 | 1
0 | 0 | 1 | 8 | 0 | 6 | 4 | 0 | 0
0 | 0 | 8 | 1 | 0 | 2 | 9 | 0 | 0
7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8
0 | 0 | 6 | 7 | 0 | 8 | 2 | 0 | 0
0 | 0 | 2 | 6 | 0 | 9 | 5 | 0 | 0
8 | 0 | 0 | 2 | 0 | 3 | 0 | 0 | 9
0 | 0 | 5 | 0 | 1 | 0 | 3 | 0 | 0

1 个答案:

答案 0 :(得分:3)

rows = ("|".join(map(" {:2d} ".format, row)) for row in p)
print("\n".join(rows))

Output

 -8 |  0 |  0 |  0 |  0 |  0 |  0 |  0 |  0 
  0 |  0 | -3 | -6 |  0 |  0 |  0 |  0 |  0 
  0 | -7 |  0 |  0 | -9 |  0 | -2 |  0 |  0 
  0 | -5 |  0 |  0 |  0 | -7 |  0 |  0 |  0 
  0 |  0 |  0 |  0 | -4 | -5 | -7 |  0 |  0 
  0 |  0 |  0 | -1 |  0 |  0 |  0 | -3 |  0 
  0 |  0 | -1 |  0 |  0 |  0 |  0 | -6 | -8 
  0 |  0 | -8 | -5 |  0 |  0 |  0 | -1 |  0 
  0 | -9 |  0 |  0 |  0 |  0 | -4 |  0 |  0