2

我有列表列表:

[['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']]]

请问有人可以帮助我吗?

4

3 回答 3

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']]]
于 2012-11-29T04:13:46.270 回答
2

我建议你先浏览这些链接

for_loops

创建字典的方法

如何-我-将-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']]]
于 2012-11-29T04:11:56.683 回答
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())
于 2012-11-29T04:19:24.157 回答