Chrystael
Chrystael

Reputation: 179

Ordering a list of tuples in python

I have a list, my_list:

[['28/02/2014, apples']
['09/07/2014, oranges']
['22/04/2014, bananas']
['14/03/2014, tomatoes']]

which I am trying to order by date. This is the code I am using:

def display(my_list):
    for item in my_list:
        x = ([item[0] + ": " + item[1]])
        print x

I've tried applying different forms of sorting to x (sorted, x.sort(), etc) but nothing seems to work. How can I get the list to sort by date, from earliest to latest?

Upvotes: 3

Views: 109

Answers (1)

alecxe
alecxe

Reputation: 474171

You can use sorted() with applying a key function that takes the first item from every sublist, splits it by : and converts the part before the colon to datetime using strptime():

>>> from datetime import datetime
>>> l = [['28/02/2014: apples'], ['09/07/2014: oranges'], ['22/04/2014: bananas'], ['14/03/2014: tomatoes']]
>>> sorted(l, key=lambda x: datetime.strptime(x[0].split(':')[0], '%d/%m/%Y'))
[['28/02/2014: apples'],  
 ['14/03/2014: tomatoes'], 
 ['22/04/2014: bananas'], 
 ['09/07/2014: oranges']]

Upvotes: 6

Related Questions