Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort 2 list linked to each other

I go stuck on a problem and I cannot think of any efficient way to do this. The problem is the following:

I got 2 lists, each with n up to 10^3.

v = [v_1, v_2, ..., v_n]
w = [w_1, w_2, ..., w_n]

In the following example n = 3.

v = [60, 100 , 120] 
w = [20, 50, 30]

I need to sort both lists based on the decreasing order of the following equation: v_i/w_i

So in this case I would get:

v_1/w_1 = 3
v_2/w_2 = 2
v_3/w_3 = 4

After that I need to sort both lists (depended to each other) by the decreasing order and I would get the following result.

v_new = [120, 60, 100]
w_new = [30, 20, 50]

I know there is a way with sorted(zip(X,Y), but doing so it would change my list in a tuple and I need it as a list. Any suggestions?

like image 262
Robert Avatar asked Sep 30 '18 07:09

Robert


People also ask

How do you sort a 2 list in Python?

To sort a two-dimensional list in Python use the sort() list method, which mutates the list, or the sorted() function, which does not. Set the key parameter for both types using a lambda function and return a tuple of the columns to sort according to the required sort order.


1 Answers

Python's sort functions can take a key, you can use a lambda function to define the key you want to sort over. In this case, i'd suggest sorting the indices and then applying the order to both v and w. For example:

v = [60, 100 , 120] 
w = [20, 50, 30]
order = sorted(range(len(v)), key=lambda i: v[i] / w[i], reverse=True)

v_new = [v[i] for i in order]
w_new = [w[i] for i in order]
like image 73
Bi Rico Avatar answered Nov 15 '22 05:11

Bi Rico