def validSolution(board):
print([rank[i] for i in range(len(board[0])) for rank in board])
validSolution([[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]])
我希望它以列表的形式分别输出每一列,如下所示:
[[5,6,1,8,4,7,9,2,3],[3,7,9,5,2,1,6,8,4], etc...]
然而,我得到了这个
[5, 6, 1, 8, 4, 7, 9, 2, 3, 3, 7, 9, 5, 2, 1, 6, 8, 4, 4, 2, 8, 9, 6, 3, 1, 7, 5, 6, 1, 3, 7, 8, 9, 5, 4, 2, 7, 9, 4, 6, 5, 2, 3, 1, 8, 8, 5, 2, 1, 3, 4, 7, 9, 6, 9, 3, 5, 4, 7, 8, 2, 6, 1, 1, 4, 6, 2, 9, 5, 8, 3, 7, 2, 8, 7, 3, 1, 6, 4, 5, 9]
简单地说,它与我预期的不同,因为它没有分开。
我可以要求一个解决方案,通过列表理解来获得我想要的输出吗?
答案 0 :(得分:0)
# You can go classic:
def transpose (m):
return [[m[row][col] for row in xrange(len(m))] for col in xrange(len(m[0]))]
>>> transpose([[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]
...
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>>