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?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With