Split dates according to month python

58 views Asked by At

I have a list of dates as follows

[['2018-05-24', 6000], ['2018-05-25', 43300], ['2018-06-27', 0], ['2018-06-28', 20400], ['2018-06-03', 600], ['2018-07-03', 1100]]

I want the above array to be split as follows

[['2018-05-24', 6000], ['2018-05-25', 43300]]
['2018-06-27', 0], ['2018-06-28', 20400], ['2018-06-03', 600]]
[['2018-07-03', 1100]]

Is there any way to do this in Python?

2

There are 2 answers

0
Rakesh On

Use groupby from itertools

Ex:

from itertools import groupby
import pprint
res = []
l = [['2018-05-24', 6000], ['2018-05-25', 43300], ['2018-06-27', 0], ['2018-06-28', 20400], ['2018-06-03', 600], ['2018-07-03', 1100]]
for k, g in groupby(l, lambda x: x[0][:7]):
    res.append(list(g))

pprint.pprint(res)

Output:

[[['2018-05-24', 6000], ['2018-05-25', 43300]],
 [['2018-06-27', 0], ['2018-06-28', 20400], ['2018-06-03', 600]],
 [['2018-07-03', 1100]]]
0
Sunitha On

You can use itertools.groupby to do something similar

>>> import itertools 
>>> 
>>> l=[['2018-05-24', 6000], ['2018-05-25', 43300], ['2018-06-27', 0], ['2018-06-28', 20400], ['2018-06-03', 600], ['2018-07-03', 1100]]
>>> [list(v) for k,v in groupby(l, lambda e: e[0])]
[[['2018-05-24', 6000]], [['2018-05-25', 43300]], [['2018-06-27', 0]], [['2018-06-28', 20400]], [['2018-06-03', 600]], [['2018-07-03', 1100]]]
>>>