buddingengineer buddingengineer - 9 months ago 83
Python Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download