Jan-12-2017, 07:59 AM
(Jan-12-2017, 06:54 AM)DrLove73 Wrote: I understood that I need to use "key" function. This is the hardest part to understand.You can use
datetime.strptime
to convert it to date format,the use it in sorted()
with key
.Eg:
>>> from datetime import datetime >>> from pprint import pprint >>> ... data = '''\ ... archive.pst 2016-10-1 080101.pst ... archive.pst 2016-10-20 080101.pst ... archive.pst 2016-10-8 080101.pst''' >>> pst_files = [] >>> for line in data.split('\n'): ... pst_files.append(line.split()) >>> pprint(pst_files) [['archive.pst', '2016-10-1', '080101.pst'], ['archive.pst', '2016-10-20', '080101.pst'], ['archive.pst', '2016-10-8', '080101.pst']] >>> pprint(sorted(pst_files, key=lambda x: datetime.strptime(x[1], "%Y-%m-%d"), reverse=True)) [['archive.pst', '2016-10-20', '080101.pst'], ['archive.pst', '2016-10-8', '080101.pst'], ['archive.pst', '2016-10-1', '080101.pst']]