3

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?

Chrystael
  • 179
  • 1
  • 2
  • 8
  • 4
    I'm very confused by what your code actually looks like. That first block of code is not "a list of tuples", it is four separate single-element lists each containing exactly one string. – Two-Bit Alchemist Apr 08 '14 at 17:13
  • Sorry for the confusion - the list is actually what the function displays at the moment, without sorting. I'll try and edit it to make it a bit more clear. – Chrystael Apr 08 '14 at 17:15
  • possible duplicate of [How to sort (list/tuple) of lists/tuples?](http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – Gilles 'SO- stop being evil' Apr 08 '14 at 17:21
  • @Gilles I doubt it is a duplicate - there are dates inside of strings - it makes the question different. – alecxe Apr 08 '14 at 17:22

1 Answers1

6

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']]
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195