Skip to content Skip to sidebar Skip to footer

Python & Sorting : Sorting Elements In Order Their Subelements In An Array

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'], ['

Solution 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

Solution 2:

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']]

Solution 3:

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']
#]

Post a Comment for "Python & Sorting : Sorting Elements In Order Their Subelements In An Array"