-1

I have the following list in Python upto n:

l = [[x_1,y_1,h_1,w_1], [x_2,y_2,h_2,w_2], ..., [x_n,y_n,h_n,w_n]] 

And I need to sort it in descending order with respect to the sum of first and third elements in the sublists (x_i and h_i) and then get first n sublists.

I managed to do it by storing the sums in a new list, but is there an efficient way to sort it without creating the one?

EDIT: Sorry, this is a duplicate question indeed.

4
  • 1
    maybe with a real-life example (and actual numbers) your question would be clearer. Commented Jul 28, 2017 at 7:20
  • ok, so now your question is just "how to sort by criterion". Not very original... (and a duplicate) Commented Jul 28, 2017 at 7:27
  • Thank you very much and sorry for the duplicate! Commented Jul 28, 2017 at 8:15
  • at least you're admitting that it's a duplicate. Not everyone does that :) Commented Jul 28, 2017 at 8:17

2 Answers 2

4

You can sort a list using a specific key that you can define:

l.sort(key=lambda x: x[0] + x[2])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! That helps
2

Go to below link and see full detail how to sort in python

sorting in python

 a = sorted(l, key=lambda x: x[0] + x[2])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.