Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two arrays into a matrix in python and sort

Ok, this is a very easy question for which I could not find the solution here;

I have two lists A and B

A=(0,1,2,3,...,N-1)  (N elements)
B=(-50,-30,-10,.....,-45) (N elements)

I would like to create a new structure, kind of a 2D matrix "C" with 2xN elements so that

C(0)=(0,-50)
C(1)=(1,-30)
...
C(N)=(N-1,-45)

I could not get to this since I do not see an easy way to build such matrices.

Then I would like to get a new matrix "D" where all the elements coming from B are sorted from highest to lowest such

D(0)=(0,-50)
D(1)=(N-1,-45)
D(2)=(1,-30)
...

How could I achieve this?

P.S. Once I get "D" how could I separate it into two strings A2 and B2 like the first ones? Such

A2=(0,N-1,1,...)
B2=(-50,-45,-30,...)
like image 903
Open the way Avatar asked Jun 17 '11 17:06

Open the way


1 Answers

C = zip(A, B)
D = sorted(C, key=lambda x: x[1])
A2, B2 = zip(*D)

Or all on one line:

A2, B2 = zip(*sorted(zip(A,B), key=lambda x: x[1]))
like image 76
Peter Collingridge Avatar answered Oct 04 '22 06:10

Peter Collingridge