Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 948
Chrystael Avatar asked Feb 17 '26 23:02

Chrystael


1 Answers

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']]
like image 172
alecxe Avatar answered Feb 19 '26 11:02

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!