With Python, how to sort the lists based on the values in the list (from right to left)?
For example:
[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]
should return
[2003, 5, 21], [2003, 5, 22], [2005, 5, 11], [2005, 6, 21]
With Python, how to sort the lists based on the values in the list (from right to left)?
For example:
[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]
should return
[2003, 5, 21], [2003, 5, 22], [2005, 5, 11], [2005, 6, 21]
Based on your expected result, that's not right-to-left sorting. In that case, the default sort works just fine:
>>> xyzzy = [[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]]
>>> sorted(xyzzy)
[[2003, 5, 21], [2003, 5, 22], [2005, 5, 11], [2005, 6, 21]]
If you did want to sort based on right-to-left order in each sub-list, you can provide a key
function/callable which does the work for you. Since you want the same comparison but in reverse, just use the reversed list for the comparison:
>>> sorted(xyzzy, key=lambda x: x[::-1])
[[2005, 5, 11], [2003, 5, 21], [2005, 6, 21], [2003, 5, 22]]
Use the sorted() in python.
input_list = [2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]
sorted_list = sorted(input_list)
Declaring the input_list
like above will create a tuple of lists and input_list.sort()
will not work as sort does not support tuple. If you need to use sort(), you have to first convert the tuple of lists to list of lists and then perform sort operation like below.
input_list = [[2005, 6, 21], [2003, 5, 21], [2005, 5, 11], [2003, 5, 22]]
input_list.sort()
If you need to sort from left to right, you can use the reverse parameter.
sorted_list = sorted(input_list, reverse=True)
or
input_list.sort(reverse=True)
Note that sorted()
will return the sorted list, whereas sort()
will replace the input list with the sorted list.