1

Is there a function to convert matrices in python? example [1,2],[4,5],[7,8] => ans : [1,4,7],[2,5,8]

1
  • 3
    I would call this operation "transpose" rather than "convert" (which could mean anything). Commented Jan 25, 2014 at 7:59

2 Answers 2

3

You can use zip function, like this

l = [[1,2,3],[4,5,6],[7,8,9]]
print zip(*l)

Output

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Sign up to request clarification or add additional context in comments.

5 Comments

what a clever use of zip and argument expansion
@caoy People used to call this as argument unpacking :)
lol, thanks, i knew i shouldn't just invent names :P
@ thefourtheye if rows not equal columns. example [[1,2,3,4],[5,6,7,8],[9,0,11,12]] output [[1,5,9],[2,6,0],[3,7,11],[4,8,12]]
@pukluk It will still work. Please try that yourself :)
2

Depending on your program, you may want to use numpy:

In [1]: m = np.array([[1,2,3],[4,5,6],[7,8,9]])

In [2]: m
Out[2]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [3]: m.T
Out[3]: 
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

2 Comments

if rows not equal columns. example [[1,2,3,4],[5,6,7,8],[9,0,11,12]] output [[1,5,9],[2,6,0],[3,7,11],[4,8,12]]
This will still work in numpy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.