我有列表清单:
[['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']]]
我需要列表中包含相同日期的每个第一个值将第二个值加入到输出中,如此
[['13/03/2012', ['a', 'b', 'c', 'd', 'e', 'f']], ['26/03/2012', ['f']], ['02/04/2012', ['a']], ['09/04/2012', ['b']]]
请有人可以帮助我吗?
答案 0 :(得分:6)
您可以尝试使用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']]]
答案 1 :(得分:2)
我建议你先通过这些链接
how-can-i-convert-a-python-dictionary-to-a-list-of-tuples
这应该可以帮助你完成..
In [7]: [['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']]]
In [8]: d= {}
In [9]: for item in l:
...: if d.has_key(item[0]):
...: d[item[0]].extend(item[1])
...: else:
...: d[item[0]] = item[1]
...:
In [10]: d
Out[10]:
{'02/04/2012': ['a'],
'09/04/2012': ['b'],
'13/03/2012': ['a', 'b', 'c', 'd', 'e', 'f'],
'26/03/2012': ['f']}
In [11]: [[k,v] for k,v in d.items()]
Out[11]:
[['02/04/2012', ['a']],
['09/04/2012', ['b']],
['26/03/2012', ['f']],
['13/03/2012', ['a', 'b', 'c', 'd', 'e', 'f']]]
答案 2 :(得分:1)
与avasal类似,但这似乎是使用defaultdict的好地方
from collections import defaultdict
l = [['13/03/2012', ['a', 'b', 'c', 'd', 'e', 'f']], ['26/03/2012', ['f']], ['02/04/2012', ['a']], ['09/04/2012', ['b']]]
d = defaultdict(list)
for item in l:
d[item[0]].extend(item[1])
print map(list, d.items())