buddingengineer
buddingengineer

Reputation: 95

Python - Sorting list

I have a lists like the below:

list1 = [['4.00', '7.00'], ['4.00', '4.00'], ['4.00', '1.00']]
list2 = [['4.00', '7.00'], ['1.00', '7.00'], ['6.00', '7.00']]

If x values are equal, I want to sort the elements in ascending order based on y values and if y values are equal, want to sort based on x values like below:

sorted list1 = [['4.00', '1.00'], ['4.00', '4.00'], ['4.00', '7.00']]
sorted list2 = [['1.00', '7.00'], ['4.00', '7.00'], ['6.00', '7.00']]

I tried to use sorted(). But code becomes complicated when i try to compare the values of x to find out if they are the same and then giving key to sorted() based on that. Can I do it in a better way?

Upvotes: 0

Views: 62

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155683

sorted already does what you want. Comparing lists is done lexicographically: The elements are compared from left to right until an unequal element is found, at which point the result of the comparison is the comparison on that first unequal element. For example, with no key function at all, your lists sort as you expect:

>>> list1 = [['4.00', '7.00'], ['4.00', '4.00'], ['4.00', '1.00']]
>>> list2 = [['4.00', '7.00'], ['1.00', '7.00'], ['6.00', '7.00']]
>>> sorted(list1)
[['4.00', '1.00'], ['4.00', '4.00'], ['4.00', '7.00']]
>>> sorted(list2)
[['1.00', '7.00'], ['4.00', '7.00'], ['6.00', '7.00']]

In the list1 case, it correctly compares the first values, determines they're the same, and sorts on the second value; in the list2 case, the first values all differ, so the second value is never even checked.

Upvotes: 2

Related Questions