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?

4
  • 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. Commented Apr 8, 2014 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. Commented Apr 8, 2014 at 17:15
  • possible duplicate of How to sort (list/tuple) of lists/tuples? Commented Apr 8, 2014 at 17:21
  • @Gilles I doubt it is a duplicate - there are dates inside of strings - it makes the question different. Commented Apr 8, 2014 at 17:22

1 Answer 1

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']]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.