[Tutor] changing 2x3 matrix to 3x2 matrix - using lists

Kent Johnson kent37 at tds.net
Sat Apr 15 00:14:43 CEST 2006


Srinivas Iyyer wrote:
> Dear group, 
>  I have a huge list of data. This was obtained using R
> through Rpy. 
> 
> the data resembles a 10K (row) x 30 (column) matrix. 
> 
> I processed the data column wise( obtained median
> values for duplicated rows).
> 
> Now I am left with 500 rows and 30 columns. 
> 
> I want to print the same way. 
> 
> 
> A snippet:
> 
>>>> a = """apple\tboy\tcat\ndog\tegg\tfox\n"""
>>>> ab = a.split('\n')
>>>> for m in ab:
> 	cols = m.split('\t')
> 	print cols
> 
> 	
> ['apple', 'boy', 'cat']
> ['dog', 'egg', 'fox']
> ########################################
> # Here I processed the data and assuming nothing
> changed in the snippet, I want to print :
> ##
> apple   dog
> boy     egg
> cat     fox
> 
> How can I do that?
> I tries a different way below. If there are two lists,
> I could use 'zip' method.  However, since script is
> running over a loop of 30 columns, I have no clue how
> can I use zip dynamically.

For working with arrays that big you should probably look at numpy, but 
someone else will have to help you with that.

If you have a list of lists, you can use zip(*lists) to transpose it:
In [1]: data = [
    ...: ['apple', 'boy', 'cat'],
    ...: ['dog', 'egg', 'fox'],
    ...: ['spam', 'cheese', 'ni']
    ...: ]

In [3]: data
Out[3]: [['apple', 'boy', 'cat'], ['dog', 'egg', 'fox'], ['spam', 
'cheese', 'ni']]

In [4]: zip(*data)
Out[4]: [('apple', 'dog', 'spam'), ('boy', 'egg', 'cheese'), ('cat', 
'fox', 'ni')]

zip(*data) is like saying zip(data[0], data[1], ..., data[-1]) but you 
don't have to know how big data is.

Kent



More information about the Tutor mailing list