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']]
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']]
sorted()
sorted()
sorted
already does what you want. Comparing list
s 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.