Home > other >  Sorting Nested list in python
Sorting Nested list in python

Time:04-12

I am doing a problem that my school has assigned to me. Here is code till now:

profits = [1,2,5,6]
weights = [2,3,4,5]
n = 8
ratio = []
count = 0
for i in range(len(profits)):
    ratio.append([])
for i in range(len(ratio)):
    ratio[i].append(weights[i])
    ratio[i].append(profits[i] / weights[i])

The output (ratio):

[[2, 0.5], [3, 0.6666666666666666], [4, 1.25], [5, 1.2]]

But the problem is that I want the list to be sorted maximum ratio wise like this:

[[4, 1.25], [5, 1.2], [3, 0.6666666666666666], [2, 0.5]]

CodePudding user response:

You can pass a key parameter to .sort().

Below your current code, add:

ratio.sort(key=lambda x: x[1])

to sort on the ratio (as opposed to the default sorting mechanism, which starts at the first element in the list).

After this sorting operation, ratio will be:

[[2, 0.5], [3, 0.6666666666666666], [5, 1.2], [4, 1.25]]

CodePudding user response:

Please try:

print(sorted(ratio, key=lambda x: float(x[1]), reverse=True))

Output:

[[4, 1.25], [5, 1.2], [3, 0.66666666666666663], [2, 0.5]]
  • Related