Reputation: 13
The code i'm working with has a list of lists that contains (moviename, year released, genre, watched or unwatched). I am trying to sort the list by year released to display, however it is not sorting properly
movielist.sort(key=lambda x: x[1])
This is the code i'm trying to run to sort a list of lists by year, but it is not sorting properly.
Output is:
['Citizen Kane', '1941', 'Drama', 'u']
['Star Wars: Episode IV - A New Hope', '1977', 'Action', 'w']
['The Fugitive', '1993', 'Drama', 'u']
['Fun with Dick and Jane', '2005', 'Comedy', 'w']
['Persian-Roman War', '557', 'Action', 'u']
when it should be:
['Persian-Roman War', '557', 'Action', 'u']
['Citizen Kane', '1941', 'Drama', 'u']
['Star Wars: Episode IV - A New Hope', '1977', 'Action', 'w']
['The Fugitive', '1993', 'Drama', 'u']
['Fun with Dick and Jane', '2005', 'Comedy', 'w']
Upvotes: 1
Views: 190
Reputation: 63
when you are doing
movielist.sort(key=lambda x: x[1])
It sorts based on string values which does not work in your case
Use this instead
movielist.sort(key=lambda x: int(x[1]))
Hope this Helped
Upvotes: 3
Reputation: 521073
The issue here is that you are sorting on a text year, and lexicographically, the year 1941
is "before" 557
. You may try left padding the year with zeroes to a fixed width of 4:
movielist.sort(key=lambda x: x[1].zfill(4))
With this approach, sorting on the text year works, and would give the following order:
0557
1941
1977
1993
2005
Upvotes: 0