3

I have a list of lists that looks something like this:

dateList = [['2014', '4'], ['2015', '6'], ['2017', '6'], ['2016', '2'], ['2016', '3'], ['2017', '9'], ['2016', '6'], ['2017', '3'], ['2014', '8'], ['2014', '10'], ['2017', '10'], ['2014', '9'], ['2014', '3'], ['2015', '11'], ['2015', '2']]

I have been trying to sort it by year first, and then by month. I've been successful in sorting it by year using

sortedList = sorted(dateList, key = lambda x: int(x[0]))

However, I can't figure out a way to sort it by month afterwards while keeping the years in ascending order.

Gahan
  • 4,075
  • 4
  • 24
  • 44
Robert C
  • 65
  • 1
  • 3
  • 9

2 Answers2

5

Pass a tuple:

sorted(dateList, key = lambda x: (int(x[0]),int(x[1])))

But this looks better:

sorted(dateList, key = lambda x: tuple(map(int,x)))

And another alternative could be to use:

import datetime 
sorted(dateList, key = lambda x: datetime.datetime.strptime(''.join(x),'%Y%m'))
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
3

It seems like you're in need of a natural sorting of your data. You can use the natsort package to do this, without having to pass a key at all -

import natsort

natsort.natsorted(dateList)

[['2014', '3'],
 ['2014', '4'],
 ['2014', '8'],
 ['2014', '9'],
 ['2014', '10'],
 ['2015', '2'],
 ['2015', '6'],
 ['2015', '11'],
 ['2016', '2'],
 ['2016', '3'],
 ['2016', '6'],
 ['2017', '3'],
 ['2017', '6'],
 ['2017', '9'],
 ['2017', '10']]
cs95
  • 379,657
  • 97
  • 704
  • 746