Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining list consist of multiple lists which have same value in python

I have list of lists:

[['13/03/2012', ['a']], ['13/03/2012', ['b', 'c', 'd']], ['13/03/2012', ['e', 'f']], ['26/03/2012', ['f']], ['02/04/2012', ['a']], ['09/04/2012', ['b']]]

I need the list contain the same date in each first value will join the second value to output like this

[['13/03/2012', ['a', 'b', 'c', 'd', 'e', 'f']], ['26/03/2012', ['f']], ['02/04/2012', ['a']], ['09/04/2012', ['b']]]

Please anyone can help me?

like image 311
kuslahne Avatar asked Mar 19 '26 21:03

kuslahne


1 Answers

You could try using itertools. This groups the list by date and then iterates through the keys/groups, creating a list that has the key as the first element and the 'flattened' list values:

In [51]: from itertools import groupby

In [52]: result = []

In [53]: for key, group in groupby(l, key=lambda x: x[0]):
   ....:     inner = [key, [item for subg in group for item in subg[1]]]
   ....:     result.append(inner)
   ....:
   ....:

In [54]: result
Out[54]:
[['13/03/2012', ['a', 'b', 'c', 'd', 'e', 'f']],
 ['26/03/2012', ['f']],
 ['02/04/2012', ['a']],
 ['09/04/2012', ['b']]]

You could do this as a one-liner, but besides being over 80 characters, it is even less readable than the first version and should probably be avoided :)

In [57]: result = [[key, [item for subg in group for item in subg[1]]] for key, group in groupby(l, key=lambda x: x[0])]

In [58]: result
Out[59]:
[['13/03/2012', ['a', 'b', 'c', 'd', 'e', 'f']],
 ['26/03/2012', ['f']],
 ['02/04/2012', ['a']],
 ['09/04/2012', ['b']]]
like image 136
RocketDonkey Avatar answered Mar 22 '26 11:03

RocketDonkey