5

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,...)

1 Answer 1

9
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]))
Sign up to request clarification or add additional context in comments.

2 Comments

great! last question, how could I separate the new "D" into the new ones A2 and B2 ?
Missed the last bit first time, I've edited my answer to include it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.