0

I have an array and it has 4 elements and every element has 3 subelements;

myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]

As you see, every elements' first subelement is a date. And I want to order these elements with their dates. So I want that output when I enter print(myList);

[['26.03.2019', 'Michelle', '8'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8'], ['03.04.2019', 'Jack', '2']]

How can I do that? Can you give me a solution for this?

3 Answers 3

1

print(myList) would just print your list. You do not want to fiddle with that. What you want to do is sort your list prior to printing. Like so for example:

import datetime


myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]
myList.sort(key=lambda sublist: datetime.datetime.strptime(sublist[0], "%d.%m.%Y"))

print(myList)  # -> [['26.03.2019', 'Michelle', '8'], 
               #     ['01.04.2019', 'George', '2'], 
               #     ['02.04.2019', 'Micheal', '8'], 
               #     ['03.04.2019', 'Jack', '2']]

Note that doing myList.sort(..) permanently changes your list.. If that is not what you want, you can create a new one using sorted as @Rakesh proposes in his answer.


Kudos: the code for the sorting of the dates was taken from here

Sign up to request clarification or add additional context in comments.

Comments

1

Convert string date to datetime object and then use sorted

Ex:

import datetime
myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]

print( sorted(myList, key=lambda x: datetime.datetime.strptime(x[0], "%d.%m.%Y")) )

Output:

[['26.03.2019', 'Michelle', '8'],
 ['01.04.2019', 'George', '2'],
 ['02.04.2019', 'Micheal', '8'],
 ['03.04.2019', 'Jack', '2']]

Comments

1

Sort your list on the date string, after changing it to datetime object via strptime

import datetime
myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]

myList.sort(key=lambda x: datetime.datetime.strptime(x[0], "%d.%m.%Y"))
print(myList)
#[
#['26.03.2019', 'Michelle', '8'], 
#['01.04.2019', 'George', '2'], 
#['02.04.2019', #'Micheal', '8'], 
#['03.04.2019', 'Jack', '2']
#]

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.