Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to convert a matrix to a list python

Tags:

python

Hi there I need to convert a matrix to a list as the example below

Matrix:
[[  1.   6.  13.  10.   2.]
 [  2.   9.  10.  13.  15.]
 [  3.  15.  13.  14.  16.]
 [  4.   5.  14.  13.   6.]
 [  5.  18.  16.   4.   3.]
 [  6.   7.  12.  18.   3.]
 [  7.   1.   8.  17.  11.]
 [  8.  14.   5.   4.  16.]
 [  9.  16.  18.  17.  15.]
 [ 10.   8.   9.  15.  17.]
 [ 11.  11.  17.  18.  12.]]

List:
[(1, 6, 13, 10, 2),  (2, 9, 10, 13, 15), (3, 15, 13, 14, 16),
 (4, 5, 14, 13, 6),  (5, 18, 16, 4, 3),  (6, 7, 12, 18, 3), 
 (7, 1, 8, 17, 11),  (8, 14, 5, 4, 16),  (9, 16, 18, 17, 15),
 (10, 8, 9, 15, 17), (11, 11, 17, 18, 12)]

Thx in adavance

like image 563
Ghassen Avatar asked Oct 29 '10 03:10

Ghassen


2 Answers

Is this a numpy matrix? If so, just use the tolist() method. E.g.:

import numpy as np
x = np.matrix([[1,2,3],
               [7,1,3],
               [9,4,3]])
y = x.tolist()

This yields:

y --> [[1, 2, 3], [7, 1, 3], [9, 4, 3]]
like image 170
Joe Kington Avatar answered Sep 28 '22 20:09

Joe Kington


The best way to do it is:

result = map(tuple, Matrix)
like image 22
aaronasterling Avatar answered Sep 28 '22 20:09

aaronasterling