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 Answers3

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']]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
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

Ma0
  • 15,057
  • 4
  • 35
  • 65
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']
#]

Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40