您可以尝试使用itertools
. 这将按日期对列表进行分组,然后遍历键/组,创建一个将键作为第一个元素和“扁平化”列表值的列表:
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']]]
您可以将其作为单行来执行,但除了超过 80 个字符之外,它的可读性甚至比第一个版本还要低,应该避免使用 :)
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']]]