2
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]])

I want it to output every column separately in a form of list, like this:

[[5,6,1,8,4,7,9,2,3],[3,7,9,5,2,1,6,8,4], etc...]

however, i got this

[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]

simply put, it's different from what I had expected as it is not separated.

May I ask for a solution to get my desired output with list comprehension?

lilpig
  • 153
  • 1
  • 1
  • 10
  • You've already figured out how to transpose a list, essentially, but @EvanWeissburg identified your bug. However, there [are easier](https://stackoverflow.com/questions/6473679/transpose-list-of-lists) ways of transposing, so try `print(list(map(list, zip(*board)))` or just `print(list(zip(*board)))` if you don't mind a list of tuples... – juanpa.arrivillaga Sep 14 '17 at 23:59
  • thank you, juanpa, the map method was far better than the one i have used – lilpig Sep 15 '17 at 00:02

1 Answers1

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]]
>>>
Dalen
  • 4,128
  • 1
  • 17
  • 35