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?
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']]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With